using System.Windows;
using System.Windows.Threading;
using System.Windows.Input;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using DocumentCreationSystem.Helpers;
using DocumentCreationSystem.Services;
using DocumentCreationSystem.ViewModels;
using DocumentCreationSystem.Views;
using DocumentCreationSystem.Models;
using System.Windows.Documents;
using System.Windows.Controls;
using System.IO;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using Xceed.Words.NET;

namespace DocumentCreationSystem
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly IServiceProvider _serviceProvider;
        private readonly ILogger<MainWindow> _logger;
        private readonly IAIService _aiService;
        private readonly IProjectService _projectService;
        private readonly IDocumentService _documentService;
        private readonly IVectorService _vectorService;
        private readonly IProjectHistoryService _historyService;
        private readonly Services.ISystemMonitorService _systemMonitorService;
        private readonly IThemeService _themeService;
        private readonly IPaperWritingService _paperWritingService;
        private readonly IPatentDisclosureService _patentDisclosureService;
        private readonly DispatcherTimer _timer;
        private MainWindowViewModel? _viewModel;
        private Project? _currentProject = null; // 初始化为null以消除警告

        /// <summary>
        /// 当前项目（公共属性，供其他窗口访问）
        /// </summary>
        public Project? CurrentProject => _currentProject;

        public MainWindow(IServiceProvider serviceProvider)
        {
            ILogger<MainWindow>? logger = null;
            try
            {
                _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));

                // 获取Logger
                logger = serviceProvider.GetRequiredService<ILogger<MainWindow>>();
                _logger = logger;
                _logger.LogInformation("开始初始化MainWindow...");

                // 先初始化XAML组件
                _logger.LogInformation("正在初始化XAML组件...");
                InitializeComponent();
                _logger.LogInformation("XAML组件初始化完成");

                // 逐个获取服务，每个都有错误处理
                try
                {
                    _aiService = serviceProvider.GetRequiredService<IAIService>();
                    _logger.LogInformation("IAIService 注入成功");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "获取IAIService失败");
                    throw new InvalidOperationException("无法获取AI服务", ex);
                }

                try
                {
                    _projectService = serviceProvider.GetRequiredService<IProjectService>();
                    _logger.LogInformation("IProjectService 注入成功");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "获取IProjectService失败");
                    throw new InvalidOperationException("无法获取项目服务", ex);
                }

                try
                {
                    _documentService = serviceProvider.GetRequiredService<IDocumentService>();
                    _logger.LogInformation("IDocumentService 注入成功");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "获取IDocumentService失败");
                    throw new InvalidOperationException("无法获取文档服务", ex);
                }

                try
                {
                    _vectorService = serviceProvider.GetRequiredService<IVectorService>();
                    _logger.LogInformation("IVectorService 注入成功");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "获取IVectorService失败");
                    throw new InvalidOperationException("无法获取向量服务", ex);
                }

                try
                {
                    _historyService = serviceProvider.GetRequiredService<IProjectHistoryService>();
                    _logger.LogInformation("IProjectHistoryService 注入成功");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "获取IProjectHistoryService失败");
                    throw new InvalidOperationException("无法获取项目历史服务", ex);
                }

                try
                {
                    _systemMonitorService = serviceProvider.GetRequiredService<ISystemMonitorService>();
                    _logger.LogInformation("ISystemMonitorService 注入成功");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "获取ISystemMonitorService失败");
                    throw new InvalidOperationException("无法获取系统监控服务", ex);
                }

                try
                {
                    _themeService = serviceProvider.GetRequiredService<IThemeService>();
                    _themeService.ThemeChanged += OnThemeChanged;
                    _logger.LogInformation("IThemeService 注入成功");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "获取IThemeService失败");
                    throw new InvalidOperationException("无法获取主题服务", ex);
                }

                try
                {
                    _paperWritingService = serviceProvider.GetRequiredService<IPaperWritingService>();
                    _logger.LogInformation("IPaperWritingService 注入成功");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "获取IPaperWritingService失败");
                    throw new InvalidOperationException("无法获取论文写作服务", ex);
                }

                try
                {
                    _patentDisclosureService = serviceProvider.GetRequiredService<IPatentDisclosureService>();
                    _logger.LogInformation("IPatentDisclosureService 注入成功");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "获取IPatentDisclosureService失败");
                    throw new InvalidOperationException("无法获取专利交底书写作服务", ex);
                }

                // 初始化定时器用于更新时间
                try
                {
                    _timer = new DispatcherTimer
                    {
                        Interval = TimeSpan.FromSeconds(1)
                    };
                    _timer.Tick += Timer_Tick;
                    _timer.Start();
                    _logger.LogInformation("定时器初始化成功");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "定时器初始化失败");
                    throw new InvalidOperationException("无法初始化定时器", ex);
                }

                // 延迟初始化界面，等待UI完全加载
                try
                {
                    this.Loaded += MainWindow_Loaded;
                    _logger.LogInformation("MainWindow构造函数完成");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "界面初始化设置失败");
                    throw new InvalidOperationException("无法设置界面初始化", ex);
                }
            }
            catch (Exception ex)
            {
                // 如果logger还没有初始化，使用MessageBox显示错误
                if (logger != null)
                {
                    logger.LogError(ex, "MainWindow构造函数中发生错误");
                }

                var errorMessage = $"MainWindow初始化失败:\n\n错误类型: {ex.GetType().Name}\n错误消息: {ex.Message}";
                if (ex.InnerException != null)
                {
                    errorMessage += $"\n\n内部错误: {ex.InnerException.Message}";
                }
                errorMessage += $"\n\n堆栈跟踪:\n{ex.StackTrace}";

                MessageBox.Show(errorMessage, "MainWindow初始化错误", MessageBoxButton.OK, MessageBoxImage.Error);
                throw;
            }
        }

        private async void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                await InitializeAsync();
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "MainWindow加载时初始化失败");
                MessageBox.Show($"界面初始化失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async Task InitializeAsync()
        {
            try
            {
                _logger.LogInformation("正在初始化主窗口...");

                // 检查必要的UI控件是否存在
                if (DocumentEditorControl == null)
                {
                    throw new InvalidOperationException("DocumentEditorControl未找到");
                }

                if (ProjectTreeView == null)
                {
                    throw new InvalidOperationException("ProjectTreeView未找到");
                }

                // 设置DocumentEditor的服务依赖
                try
                {
                    DocumentEditorControl.SetServices(_vectorService, _documentService, _systemMonitorService, _aiService);
                    _logger.LogInformation("DocumentEditor服务依赖设置成功");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "设置DocumentEditor服务依赖失败");
                    throw new InvalidOperationException("无法设置DocumentEditor服务依赖", ex);
                }

                // 订阅文档保存事件
                try
                {
                    DocumentEditorControl.DocumentSaved += DocumentEditor_DocumentSaved;
                    DocumentEditorControl.EnhancedChapterRewriteRequested += DocumentEditor_EnhancedChapterRewriteRequested;
                    _logger.LogInformation("文档编辑器事件订阅成功");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "订阅文档编辑器事件失败");
                    throw new InvalidOperationException("无法订阅文档编辑器事件", ex);
                }

                // 创建并设置ViewModel（在UI初始化完成后）
                try
                {
                    _viewModel = new MainWindowViewModel(_serviceProvider);
                    DataContext = _viewModel;
                    _logger.LogInformation("ViewModel创建和设置成功");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "创建ViewModel失败");
                    throw new InvalidOperationException("无法创建ViewModel", ex);
                }

                // 手动设置项目树的数据源
                try
                {
                    ProjectTreeView.ItemsSource = _viewModel.ProjectItems;
                    _logger.LogInformation("项目树数据源设置成功");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "设置项目树数据源失败");
                    throw new InvalidOperationException("无法设置项目树数据源", ex);
                }

                // 加载历史项目列表
                try
                {
                    await LoadHistoryProjectsAsync();
                    _logger.LogInformation("历史项目列表加载成功");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "加载历史项目列表失败");
                    // 历史项目加载失败不应该阻止初始化
                }

                // 初始化系统监控
                try
                {
                    _systemMonitorService.MonitorDataUpdated += SystemMonitor_DataUpdated;
                    _systemMonitorService.StartMonitoring();
                    _logger.LogInformation("系统监控初始化成功");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "系统监控初始化失败");
                    // 系统监控失败不应该阻止初始化
                }

                // 设置状态
                try
                {
                    UpdateStatus("系统就绪", true);
                    _logger.LogInformation("状态更新成功");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "更新状态失败");
                    // 状态更新失败不应该阻止初始化
                }

                // 初始化AI模型状态显示
                try
                {
                    await UpdateAIModelStatusAsync();
                    _logger.LogInformation("AI模型状态初始化成功");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "初始化AI模型状态失败");
                    // AI模型状态初始化失败不应该阻止初始化
                }

                // 初始化暗黑模式切换按钮状态
                try
                {
                    InitializeDarkModeToggle();
                    _logger.LogInformation("暗黑模式切换按钮初始化成功");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "初始化暗黑模式切换按钮失败");
                    // 暗黑模式切换按钮初始化失败不应该阻止初始化
                }

                // 启动系统资源监控
                try
                {
                    StartSystemResourceMonitoring();
                    _logger.LogInformation("系统资源监控启动成功");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "启动系统资源监控失败");
                    // 系统资源监控失败不应该阻止初始化
                }

                // 初始化状态栏AI模型信息
                try
                {
                    await UpdateAIModelStatusAsync();
                    _logger.LogInformation("状态栏AI模型信息初始化成功");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "初始化状态栏AI模型信息失败");
                    // 状态栏初始化失败不应该阻止初始化
                }

                _logger.LogInformation("主窗口初始化完成");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "初始化主窗口时发生错误");
                try
                {
                    UpdateStatus($"初始化失败: {ex.Message}", false);
                }
                catch
                {
                    // 如果连状态更新都失败了，忽略这个错误
                }
                throw; // 重新抛出异常，让调用者知道初始化失败
            }
        }

        private void Timer_Tick(object? sender, EventArgs e)
        {
            // 时间信息现在不在主界面显示，可以在需要时添加到文档编辑器状态栏
        }

        /// <summary>
        /// 主题变更事件处理
        /// </summary>
        private void OnThemeChanged(object? sender, ThemeChangedEventArgs e)
        {
            try
            {
                // 通知文档编辑器更新主题
                if (DocumentEditorControl != null)
                {
                    DocumentEditorControl.OnThemeChanged();
                }

                _logger.LogInformation($"主题已更新: {e.NewTheme.BaseTheme}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理主题变更事件时发生错误");
            }
        }

        private async void DocumentEditor_DocumentSaved(object? sender, Controls.DocumentEditor.DocumentSavedEventArgs e)
        {
            try
            {
                _logger.LogInformation($"文档已保存: {e.FilePath}");

                // 如果当前有选中的项目，更新项目路径
                if (_currentProject != null)
                {
                    DocumentEditorControl.CurrentProjectPath = _currentProject.RootPath;
                }

                // 更新状态
                UpdateStatus($"文档已保存: {Path.GetFileName(e.FilePath)}", true);

                // 如果文档在项目文件夹中，刷新项目导航
                if (_currentProject != null && e.FilePath.StartsWith(_currentProject.RootPath))
                {
                    await RefreshProjectNavigation();
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理文档保存事件时发生错误");
                UpdateStatus("文档保存后处理失败", false);
            }
        }



        /// <summary>
        /// 处理增强的章节重写请求
        /// </summary>
        private async void DocumentEditor_EnhancedChapterRewriteRequested(object? sender, Models.EnhancedChapterRewriteEventArgs e)
        {
            try
            {
                _logger.LogInformation($"收到增强章节重写请求: 第{e.Config.ChapterNumber}章, 续写: {e.IsResume}");

                // 检查当前项目
                if (_currentProject == null)
                {
                    MessageBox.Show("请先打开一个项目", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    DocumentEditorControl?.HideAIProcessingStatus();
                    return;
                }

                // 获取或创建章节重写服务
                var chapterRewriteService = GetOrCreateChapterRewriteService();

                // 创建进度报告
                var progress = new Progress<(int progress, string message)>((report) =>
                {
                    DocumentEditorControl?.ShowAIProcessingStatus($"{report.message} ({report.progress}%)");
                    UpdateStatus(report.message, true);
                });

                bool success;
                if (e.IsResume)
                {
                    // 续写操作
                    success = await chapterRewriteService.ResumeRewriteAsync(e.Config, progress);
                }
                else
                {
                    // 新的重写操作
                    success = await chapterRewriteService.StartRewriteAsync(e.Config, progress);
                }

                if (success)
                {
                    // 重新加载文档内容
                    if (File.Exists(e.Config.ChapterFilePath))
                    {
                        var newContent = await File.ReadAllTextAsync(e.Config.ChapterFilePath);
                        DocumentEditorControl.Text = newContent;
                    }

                    DocumentEditorControl?.HideAIProcessingStatus();
                    UpdateStatus($"第{e.Config.ChapterNumber}章重写完成", true);

                    // 刷新项目导航
                    await RefreshProjectNavigation();
                }
                else
                {
                    DocumentEditorControl?.HideAIProcessingStatus();
                    UpdateStatus($"第{e.Config.ChapterNumber}章重写失败", false);
                    MessageBox.Show($"第{e.Config.ChapterNumber}章重写失败：{e.Config.ErrorMessage}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "增强章节重写时发生错误");
                DocumentEditorControl?.HideAIProcessingStatus();
                UpdateStatus("章节重写失败", false);
                MessageBox.Show($"章节重写时发生错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 从文件名中提取章节号
        /// </summary>
        private int ExtractChapterNumber(string fileName)
        {
            // 尝试多种模式匹配章节号
            var patterns = new[]
            {
                @"第(\d+)章",
                @"章(\d+)",
                @"Chapter(\d+)",
                @"_章(\d+)",
                @"章节(\d+)"
            };

            foreach (var pattern in patterns)
            {
                var match = System.Text.RegularExpressions.Regex.Match(fileName, pattern);
                if (match.Success && int.TryParse(match.Groups[1].Value, out int chapterNum))
                {
                    return chapterNum;
                }
            }

            return 0;
        }

        /// <summary>
        /// 查找章节细纲文件
        /// </summary>
        private string FindChapterOutlineFile(string projectPath, int chapterNumber)
        {
            var possiblePaths = new[]
            {
                Path.Combine(projectPath, "大纲", "章节", $"chapter_{chapterNumber:D3}_outline.txt"),
                Path.Combine(projectPath, "大纲", "章节", $"第{chapterNumber}章细纲.txt"),
                Path.Combine(projectPath, "大纲", $"第{chapterNumber}章.txt"),
                Path.Combine(projectPath, $"第{chapterNumber}章细纲.txt")
            };

            foreach (var path in possiblePaths)
            {
                if (File.Exists(path))
                    return path;
            }

            return string.Empty;
        }

        /// <summary>
        /// 构建章节重写的上下文信息（最多4个参考文件）
        /// </summary>
        private async Task<string> BuildChapterRewriteContextAsync(string projectPath, int chapterNumber)
        {
            var context = new List<string>();

            // 1. 添加全书大纲
            var overallOutlinePath = Path.Combine(projectPath, "大纲", "overall_outline.txt");
            if (File.Exists(overallOutlinePath))
            {
                var outline = await File.ReadAllTextAsync(overallOutlinePath);
                if (outline.Length > 800)
                    outline = outline.Substring(0, 800) + "...";
                context.Add($"全书大纲：{outline}");
            }

            // 2. 添加角色设定
            var charactersPath = Path.Combine(projectPath, "Characters");
            if (Directory.Exists(charactersPath))
            {
                var characterFiles = Directory.GetFiles(charactersPath, "*.txt").Take(2);
                foreach (var file in characterFiles)
                {
                    var content = await File.ReadAllTextAsync(file);
                    if (content.Length > 500)
                        content = content.Substring(0, 500) + "...";
                    context.Add($"角色设定：{content}");
                }
            }

            // 3. 添加前一章内容摘要
            if (chapterNumber > 1)
            {
                var prevChapterFiles = Directory.GetFiles(Path.Combine(projectPath, "章节"), "*.txt")
                    .Where(f => Path.GetFileName(f).Contains($"第{chapterNumber - 1}章") ||
                               Path.GetFileName(f).Contains($"章{chapterNumber - 1:D4}"))
                    .FirstOrDefault();

                if (!string.IsNullOrEmpty(prevChapterFiles) && File.Exists(prevChapterFiles))
                {
                    var prevContent = await File.ReadAllTextAsync(prevChapterFiles);
                    if (prevContent.Length > 500)
                        prevContent = prevContent.Substring(0, 500) + "...";
                    context.Add($"前章内容摘要：{prevContent}");
                }
            }

            return string.Join("\n\n", context);
        }

        private void UpdateStatus(string message, bool isSuccess)
        {
            // 状态信息现在显示在文档编辑器的状态栏中
            DocumentEditorControl?.UpdateDocumentStatus(message);
            _logger.LogInformation($"状态更新: {message}");
        }

        /// <summary>
        /// 更新底部状态栏的AI模型信息
        /// </summary>
        private async Task UpdateAIModelStatusAsync()
        {
            try
            {
                var configService = App.ServiceProvider?.GetService<IAIModelConfigService>();
                if (configService == null)
                {
                    CurrentAIModelText.Text = "AI模型: 服务未初始化";
                    return;
                }

                var config = await configService.GetConfigAsync();
                var currentModel = _aiService?.GetCurrentModel();

                var platformName = config.Platform ?? "未配置";
                var modelName = currentModel?.Name ?? GetSelectedModelFromConfig(config) ?? "未选择";

                CurrentAIModelText.Text = $"AI模型: {platformName} - {modelName}";

                // 更新当前项目信息
                if (_currentProject != null)
                {
                    CurrentProjectText.Text = $"当前项目: {_currentProject.Name}";
                }
                else
                {
                    CurrentProjectText.Text = "当前项目: 无";
                }

                _logger.LogInformation($"状态栏AI模型信息已更新: {platformName} - {modelName}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新AI模型状态失败");
                CurrentAIModelText.Text = "AI模型: 更新失败";
            }
        }

        /// <summary>
        /// 从配置中获取选中的模型名称
        /// </summary>
        private string? GetSelectedModelFromConfig(AIModelConfig config)
        {
            return config.Platform switch
            {
                "Ollama" => config.OllamaConfig?.SelectedModel,
                "LMStudio" => config.LMStudioConfig?.SelectedModel,
                "ZhipuAI" => config.ZhipuAIConfig?.Model,
                "DeepSeek" => config.DeepSeekConfig?.Model,
                "OpenAI" => config.OpenAIConfig?.Model,
                "Alibaba" => config.AlibabaConfig?.Model,
                "RWKV" => config.RWKVConfig?.SelectedModel,
                _ => null
            };
        }

        /// <summary>
        /// 启动系统资源监控
        /// </summary>
        private void StartSystemResourceMonitoring()
        {
            var timer = new System.Windows.Threading.DispatcherTimer
            {
                Interval = TimeSpan.FromSeconds(2)
            };

            timer.Tick += async (s, e) =>
            {
                try
                {
                    await UpdateSystemResourceStatus();
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "更新系统资源状态失败");
                }
            };

            timer.Start();
        }

        /// <summary>
        /// 更新系统资源状态
        /// </summary>
        private async Task UpdateSystemResourceStatus()
        {
            try
            {
                // 获取CPU使用率
                var cpuUsage = await GetCpuUsageAsync();
                CPUUsageText.Text = $"CPU: {cpuUsage:F1}%";

                // 获取GPU使用率
                var gpuUsage = await GetGpuUsageAsync();
                GPUUsageText.Text = $"GPU: {gpuUsage:F1}%";
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取系统资源信息失败");
                CPUUsageText.Text = "CPU: --";
                GPUUsageText.Text = "GPU: --";
            }
        }

        /// <summary>
        /// 获取CPU使用率
        /// </summary>
        private async Task<float> GetCpuUsageAsync()
        {
            try
            {
                using var process = new System.Diagnostics.Process
                {
                    StartInfo = new System.Diagnostics.ProcessStartInfo
                    {
                        FileName = "wmic",
                        Arguments = "cpu get loadpercentage /value",
                        UseShellExecute = false,
                        RedirectStandardOutput = true,
                        CreateNoWindow = true
                    }
                };

                process.Start();
                var output = await process.StandardOutput.ReadToEndAsync();
                await process.WaitForExitAsync();

                var lines = output.Split('\n');
                foreach (var line in lines)
                {
                    if (line.StartsWith("LoadPercentage="))
                    {
                        var value = line.Substring("LoadPercentage=".Length).Trim();
                        if (float.TryParse(value, out var usage))
                        {
                            return usage;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取CPU使用率失败");
            }

            return 0;
        }

        /// <summary>
        /// 获取GPU使用率
        /// </summary>
        private async Task<float> GetGpuUsageAsync()
        {
            try
            {
                using var process = new System.Diagnostics.Process
                {
                    StartInfo = new System.Diagnostics.ProcessStartInfo
                    {
                        FileName = "nvidia-smi",
                        Arguments = "--query-gpu=utilization.gpu --format=csv,noheader,nounits",
                        UseShellExecute = false,
                        RedirectStandardOutput = true,
                        CreateNoWindow = true
                    }
                };

                process.Start();
                var output = await process.StandardOutput.ReadToEndAsync();
                await process.WaitForExitAsync();

                if (process.ExitCode == 0 && !string.IsNullOrWhiteSpace(output))
                {
                    var value = output.Trim();
                    if (float.TryParse(value, out var usage))
                    {
                        return usage;
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取GPU使用率失败");
            }

            return 0;
        }



        // 事件处理方法
        private async void PolishText_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(DocumentEditorControl.SelectedText))
                {
                    var selectedText = DocumentEditorControl.SelectedText;
                    UpdateStatus("正在润色文本...", true);

                    // 显示AI处理状态
                    DocumentEditorControl.ShowAIProcessingStatus("正在润色文本...");

                    var polishedText = await _aiService.PolishTextAsync(selectedText, "文学");

                    // 隐藏AI处理状态
                    DocumentEditorControl.HideAIProcessingStatus();

                    // 使用新的润色预览功能
                    DocumentEditorControl.ShowPolishPreview(selectedText, polishedText);

                    UpdateStatus("文本润色完成，请在右侧预览区域查看结果", true);
                }
                else
                {
                    UpdateStatus("请先选择要润色的文本", false);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "润色文本时发生错误");
                DocumentEditorControl.HideAIProcessingStatus();
                UpdateStatus("润色失败", false);
            }
        }

        private async void ExpandText_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var selectedText = DocumentEditorControl.SelectedText;
                if (string.IsNullOrWhiteSpace(selectedText))
                {
                    MessageBox.Show("请先选择要扩写的文本内容。", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                DocumentEditorControl.ShowAIProcessingStatus("正在扩写内容...");

                // 计算目标长度（原文长度的1.5-2倍）
                var targetLength = Math.Max(selectedText.Length * 2, 500);
                var expandedText = await _aiService.ExpandTextAsync(selectedText, targetLength, "");

                // 使用新的扩写预览控件
                DocumentEditorControl.ShowExpandPreview(selectedText, expandedText, true);
                DocumentEditorControl.HideAIProcessingStatus();
                UpdateStatus("内容扩写完成，请在预览区域查看结果", true);
            }
            catch (Exception ex)
            {
                DocumentEditorControl.HideAIProcessingStatus();
                _logger.LogError(ex, "扩写内容时发生错误");
                MessageBox.Show($"扩写内容时发生错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }



        private Views.OneClickWritingDialog? _oneClickWritingDialog;

        private void OneClickWriting_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                UpdateStatus("正在打开一键写书设定窗口...", false);

                // 检查是否有打开的项目
                if (_currentProject == null)
                {
                    _logger.LogWarning("一键写书功能：当前项目为空");
                    MessageHelper.ShowInformation(
                        "请先打开一个项目才能使用一键写书功能。",
                        "提示",
                        "调试信息：当前项目状态为空\n\n请通过项目导航区域打开或创建一个项目文件夹，然后再使用一键写书功能。",
                        this);
                    return;
                }

                _logger.LogInformation($"一键写书功能：当前项目 - 名称: {_currentProject.Name}, 路径: {_currentProject.RootPath}");

                // 如果悬浮窗口已存在，直接显示
                if (_oneClickWritingDialog != null)
                {
                    _oneClickWritingDialog.Show();
                    _oneClickWritingDialog.Activate();
                    UpdateStatus("一键写书设定窗口已打开", true);
                    return;
                }

                // 创建一键写书悬浮窗口
                _oneClickWritingDialog = new Views.OneClickWritingDialog(App.ServiceProvider);
                _oneClickWritingDialog.Owner = this;

                // 订阅AI输出事件
                _oneClickWritingDialog.AIOutputGenerated += Dialog_AIOutputGenerated;
                _oneClickWritingDialog.DocumentEditorUpdateRequested += Dialog_DocumentEditorUpdateRequested;
                _oneClickWritingDialog.ProjectNavigationRefreshRequested += Dialog_ProjectNavigationRefreshRequested;

                // 设置参考内容（文档编辑器中的内容）
                var referenceContent = DocumentEditorControl.Text;
                if (!string.IsNullOrWhiteSpace(referenceContent))
                {
                    _oneClickWritingDialog.ReferenceContent = referenceContent;
                }

                // 设置当前项目
                _oneClickWritingDialog.CurrentProject = _currentProject;

                // 连接进度更新事件
                var progressService = App.ServiceProvider.GetRequiredService<WritingProgressService>();
                progressService.DocumentEditorContentUpdated += OnDocumentEditorContentUpdated;

                // 处理窗口关闭事件
                _oneClickWritingDialog.Closed += (s, args) =>
                {
                    // 断开事件连接
                    progressService.DocumentEditorContentUpdated -= OnDocumentEditorContentUpdated;
                    if (_oneClickWritingDialog != null)
                    {
                        _oneClickWritingDialog.AIOutputGenerated -= Dialog_AIOutputGenerated;
                        _oneClickWritingDialog.DocumentEditorUpdateRequested -= Dialog_DocumentEditorUpdateRequested;
                        _oneClickWritingDialog.ProjectNavigationRefreshRequested -= Dialog_ProjectNavigationRefreshRequested;
                        _oneClickWritingDialog = null;
                    }

                    // 刷新项目文件夹显示
                    if (_currentProject != null)
                    {
                        LoadProjectFolder(_currentProject.RootPath);
                    }

                    // 隐藏AI处理状态
                    DocumentEditorControl.HideAIProcessingStatus();
                    DocumentEditorControl.UpdateDocumentStatus("就绪");

                    UpdateStatus("一键写书设定窗口已关闭", true);
                };

                // 显示悬浮窗口
                _oneClickWritingDialog.Show();
                UpdateStatus("一键写书设定窗口已打开", true);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "打开一键写书设定窗口时发生错误");
                UpdateStatus("打开一键写书设定窗口失败", false);
                MessageHelper.ShowError(
                    "打开一键写书设定窗口时发生错误。",
                    ex,
                    "错误",
                    this);
            }
        }

        private Views.StepByStepWritingDialog? _stepByStepWritingDialog;
        private Views.AgentChatDialog? _agentChatDialog;
        private Views.ProjectManagementDialog? _projectManagementDialog;
        private Views.AutonomousPlanningDialog? _autonomousPlanningDialog;

        private void StepByStepWriting_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                UpdateStatus("正在打开分步执行写书窗口...", false);

                // 检查是否有打开的项目
                if (_currentProject == null)
                {
                    _logger.LogWarning("分步执行写书功能：当前项目为空");
                    MessageBox.Show("请先打开一个项目才能使用分步执行写书功能。", "提示",
                        MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                _logger.LogInformation($"分步执行写书功能：当前项目 - 名称: {_currentProject.Name}, 路径: {_currentProject.RootPath}");

                // 如果窗口已存在，直接显示
                if (_stepByStepWritingDialog != null)
                {
                    _stepByStepWritingDialog.Show();
                    _stepByStepWritingDialog.Activate();
                    UpdateStatus("分步执行写书窗口已打开", true);
                    return;
                }

                // 手动创建分步执行写书服务
                var aiService = App.ServiceProvider?.GetService<IAIService>();
                var novelCreationService = App.ServiceProvider?.GetService<INovelCreationService>();
                var dataStorage = App.ServiceProvider?.GetService<IDataStorageService>();
                var worldSettingService = App.ServiceProvider?.GetService<WorldSettingService>();
                var stepByStepLogger = App.ServiceProvider?.GetService<ILogger<StepByStepWritingService>>();
                var networkRecovery = App.ServiceProvider?.GetService<NetworkRecoveryService>();
                var resumableCreation = App.ServiceProvider?.GetService<ResumableCreationService>();

                if (aiService == null || novelCreationService == null || dataStorage == null ||
                    worldSettingService == null || stepByStepLogger == null)
                {
                    MessageBox.Show("无法获取必要的服务", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                var fileNamingService = App.ServiceProvider?.GetService<IFileNamingService>();
                if (fileNamingService == null)
                {
                    MessageBox.Show("无法获取文件命名服务", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                var contentQualityService = App.ServiceProvider?.GetService<ContentQualityService>();
                if (contentQualityService == null)
                {
                    MessageBox.Show("无法获取内容质量检查服务", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                // 获取其他必需的服务
                var continuityService = App.ServiceProvider?.GetService<ChapterContinuityService>();
                if (continuityService == null)
                {
                    MessageBox.Show("无法获取章节连续性服务", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                var enhancedWorldSettingManager = App.ServiceProvider?.GetService<EnhancedWorldSettingManager>();
                if (enhancedWorldSettingManager == null)
                {
                    MessageBox.Show("无法获取增强世界设定管理器", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                var chapterSaveService = App.ServiceProvider?.GetService<UnifiedChapterSaveService>();
                if (chapterSaveService == null)
                {
                    MessageBox.Show("无法获取章节保存服务", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                var projectToolsService = App.ServiceProvider?.GetService<IProjectToolsService>();

                var stepByStepService = new StepByStepWritingService(
                    stepByStepLogger, aiService, novelCreationService, dataStorage, worldSettingService,
                    continuityService, enhancedWorldSettingManager, fileNamingService, contentQualityService,
                    chapterSaveService, projectToolsService, networkRecovery, resumableCreation, App.ServiceProvider);

                var logger = App.ServiceProvider?.GetService<ILogger<Views.StepByStepWritingDialog>>();
                if (logger == null)
                {
                    MessageBox.Show("无法获取日志服务", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                var bookBasicInfoService = App.ServiceProvider?.GetService<IBookBasicInfoService>();
                if (bookBasicInfoService == null)
                {
                    MessageBox.Show("无法获取书籍基本信息服务", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                _stepByStepWritingDialog = new Views.StepByStepWritingDialog(logger, stepByStepService, bookBasicInfoService, chapterSaveService);
                _stepByStepWritingDialog.Owner = this;
                _stepByStepWritingDialog.CurrentProject = _currentProject;

                // 订阅事件
                _stepByStepWritingDialog.ProjectNavigationRefreshRequested += StepByStep_ProjectNavigationRefreshRequested;
                _stepByStepWritingDialog.DocumentEditorUpdateRequested += StepByStep_DocumentEditorUpdateRequested;

                // 处理窗口关闭事件
                _stepByStepWritingDialog.Closed += (s, args) =>
                {
                    _stepByStepWritingDialog = null;
                    UpdateStatus("分步执行写书窗口已关闭", true);
                };

                // 显示窗口
                _stepByStepWritingDialog.Show();
                UpdateStatus("分步执行写书窗口已打开", true);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "打开分步执行写书窗口时发生错误");
                UpdateStatus("打开分步执行写书窗口失败", false);
                MessageBox.Show($"打开分步执行写书窗口时发生错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 处理分步执行写书对话框中的项目导航刷新请求
        /// </summary>
        private void StepByStep_ProjectNavigationRefreshRequested(object? sender, EventArgs e)
        {
            try
            {
                Dispatcher.Invoke(async () =>
                {
                    if (_currentProject != null)
                    {
                        await RefreshProjectNavigation();
                        _logger.LogInformation("项目导航已刷新（分步执行写书触发）");
                    }
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "刷新项目导航时发生错误（分步执行写书触发）");
            }
        }

        /// <summary>
        /// 处理分步执行写书对话框中的文档编辑器更新请求
        /// </summary>
        private void StepByStep_DocumentEditorUpdateRequested(object? sender, string content)
        {
            try
            {
                Dispatcher.Invoke(() =>
                {
                    // 更新文档编辑器内容
                    DocumentEditorControl.Text += content;
                    _logger.LogInformation("文档编辑器内容已更新（分步执行写书触发）");
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新文档编辑器内容时发生错误（分步执行写书触发）");
            }
        }

        private void AIAssistantHeader_DoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            try
            {
                UpdateStatus("正在打开AI Agent对话框...", false);

                // 检查是否有打开的项目
                if (_currentProject == null)
                {
                    _logger.LogWarning("AI Agent对话框：当前项目为空");
                    MessageBox.Show("请先打开一个项目才能使用AI Agent功能。", "提示",
                        MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                _logger.LogInformation($"AI Agent对话框：当前项目 - 名称: {_currentProject.Name}, 路径: {_currentProject.RootPath}");

                // 如果窗口已存在，直接显示
                if (_agentChatDialog != null)
                {
                    _agentChatDialog.Show();
                    _agentChatDialog.Activate();
                    UpdateStatus("AI Agent对话框已打开", true);
                    return;
                }

                // 创建AI Agent对话框
                var agentToolService = App.ServiceProvider?.GetService<AgentToolService>();
                var aiService = App.ServiceProvider?.GetService<IAIService>();
                var projectService = App.ServiceProvider?.GetService<IProjectService>();
                var aiToolsService = App.ServiceProvider?.GetService<IAIToolsService>();
                var logger = App.ServiceProvider?.GetService<ILogger<Views.AgentChatDialog>>();

                if (agentToolService == null || aiService == null || projectService == null || aiToolsService == null || logger == null)
                {
                    MessageBox.Show("无法获取必要的服务", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                _agentChatDialog = new Views.AgentChatDialog(logger, agentToolService, aiService, projectService, aiToolsService);
                _agentChatDialog.Owner = this;
                _agentChatDialog.CurrentProject = _currentProject;

                // 处理窗口关闭事件
                _agentChatDialog.Closed += (s, args) =>
                {
                    _agentChatDialog = null;
                    UpdateStatus("AI Agent对话框已关闭", true);
                };

                // 显示窗口
                _agentChatDialog.Show();
                UpdateStatus("AI Agent对话框已打开", true);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "打开AI Agent对话框时发生错误");
                UpdateStatus("打开AI Agent对话框失败", false);
                MessageHelper.ShowError(
                    "打开AI Agent对话框时发生错误。",
                    ex,
                    "错误",
                    this);
            }
        }

        private void ProjectManagement_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                UpdateStatus("正在打开项目管理窗口...", false);

                // 如果窗口已存在，直接显示
                if (_projectManagementDialog != null)
                {
                    _projectManagementDialog.Show();
                    _projectManagementDialog.Activate();
                    UpdateStatus("项目管理窗口已打开", true);
                    return;
                }

                // 创建项目管理对话框
                var dataStorage = App.ServiceProvider?.GetService<IDataStorageService>();
                var logger = App.ServiceProvider?.GetService<ILogger<Views.ProjectManagementDialog>>();

                if (dataStorage == null || logger == null)
                {
                    MessageBox.Show("无法获取必要的服务", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                _projectManagementDialog = new Views.ProjectManagementDialog(logger, dataStorage);
                _projectManagementDialog.Owner = this;

                // 订阅项目选择事件
                _projectManagementDialog.ProjectSelected += ProjectManagement_ProjectSelected;

                // 处理窗口关闭事件
                _projectManagementDialog.Closed += (s, args) =>
                {
                    _projectManagementDialog = null;
                    UpdateStatus("项目管理窗口已关闭", true);
                };

                // 显示窗口
                _projectManagementDialog.Show();
                UpdateStatus("项目管理窗口已打开", true);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "打开项目管理窗口时发生错误");
                UpdateStatus("打开项目管理窗口失败", false);
                MessageBox.Show($"打开项目管理窗口时发生错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void ProjectManagement_ProjectSelected(object? sender, Project project)
        {
            try
            {
                _logger.LogInformation($"从项目管理中选择项目: {project.Name}");

                // 设置当前项目
                _currentProject = project;

                // 更新UI
                UpdateProjectInfoDisplay();
                await RefreshProjectNavigation();

                // 更新状态
                UpdateStatus($"已打开项目: {project.Name}", true);

                _logger.LogInformation($"项目已成功打开: {project.Name}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"打开选中的项目失败: {project.Name}");
                MessageBox.Show($"打开项目失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 处理一键写书对话框中的AI输出生成事件
        /// </summary>
        private void Dialog_AIOutputGenerated(object? sender, AIOutputEventArgs e)
        {
            try
            {
                // 在UI线程中更新预览区域
                Dispatcher.Invoke(() => {
                    var title = $"{e.ChapterTitle} ({e.ContentType})";
                    ShowPreviewArea(e.Content, title);
                    _logger.LogInformation($"AI输出预览已更新: {title}, 字数: {e.WordCount}");
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理AI输出事件时发生错误");
            }
        }

        /// <summary>
        /// 处理一键写书对话框中的文档编辑器更新请求
        /// </summary>
        private void Dialog_DocumentEditorUpdateRequested(object? sender, string content)
        {
            try
            {
                // 在UI线程中更新文档编辑器内容
                Dispatcher.Invoke(() =>
                {
                    if (DocumentEditorControl != null)
                    {
                        // 实时显示AI正在处理的内容
                        DocumentEditorControl.Text = content;

                        // 显示AI处理状态
                        DocumentEditorControl.ShowAIProcessingStatus("AI正在创作章节...");

                        // 更新文档状态
                        DocumentEditorControl.UpdateDocumentStatus("AI创作中...");

                        // 滚动到底部
                        if (DocumentEditorControl.TextEditor != null)
                        {
                            var lineCount = DocumentEditorControl.TextEditor.Document.LineCount;
                            DocumentEditorControl.TextEditor.ScrollToLine(lineCount);
                        }
                    }
                });

                _logger.LogInformation("文档编辑器实时内容已更新");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新文档编辑器实时内容时发生错误");
            }
        }

        /// <summary>
        /// 处理一键写书对话框中的项目导航刷新请求
        /// </summary>
        private void Dialog_ProjectNavigationRefreshRequested(object? sender, EventArgs e)
        {
            try
            {
                // 在UI线程中刷新项目导航
                Dispatcher.Invoke(async () =>
                {
                    if (_currentProject != null)
                    {
                        await RefreshProjectNavigation();
                        _logger.LogInformation("项目导航已刷新（一键写书触发）");
                    }
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "刷新项目导航时发生错误（一键写书触发）");
            }
        }

        /// <summary>
        /// 处理文档编辑器内容更新事件
        /// </summary>
        private void OnDocumentEditorContentUpdated(string content)
        {
            try
            {
                // 在UI线程中更新文档编辑器内容
                Dispatcher.Invoke(() =>
                {
                    if (DocumentEditorControl != null)
                    {
                        // 追加内容到文档编辑器
                        DocumentEditorControl.Text += content;

                        // 滚动到底部
                        if (DocumentEditorControl.TextEditor != null)
                        {
                            DocumentEditorControl.TextEditor.ScrollToEnd();
                        }
                    }
                });

                _logger.LogInformation("文档编辑器内容已更新");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新文档编辑器内容时发生错误");
            }
        }

        #region 新增AI助手功能按钮事件

        /// <summary>
        /// 总结内容
        /// </summary>
        private async void SummarizeText_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var selectedText = DocumentEditorControl.SelectedText;
                if (string.IsNullOrWhiteSpace(selectedText))
                {
                    MessageBox.Show("请先选择要总结的文本内容。", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                DocumentEditorControl.ShowAIProcessingStatus("正在总结内容...");
                var prompt = $"请对以下内容进行总结，提取关键信息和要点：\n\n{selectedText}";
                var result = await _aiService.GenerateTextAsync(prompt);

                ShowPreviewArea(result, "内容总结");
                DocumentEditorControl.HideAIProcessingStatus();
            }
            catch (Exception ex)
            {
                DocumentEditorControl.HideAIProcessingStatus();
                _logger.LogError(ex, "总结内容时发生错误");
                MessageBox.Show($"总结内容时发生错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 翻译文本
        /// </summary>
        private async void TranslateText_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var selectedText = DocumentEditorControl.SelectedText;
                if (string.IsNullOrWhiteSpace(selectedText))
                {
                    MessageBox.Show("请先选择要翻译的文本内容。", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                DocumentEditorControl.ShowAIProcessingStatus("正在翻译文本...");

                // 智能检测语言并生成翻译提示词
                var isChineseText = ContainsChinese(selectedText);
                var targetLanguage = isChineseText ? "英文" : "中文";
                var prompt = $@"请将以下文本翻译成{targetLanguage}，要求：
1. 保持原文的语义和语调
2. 确保翻译自然流畅
3. 专业术语请准确翻译
4. 只返回翻译结果，不要添加任何解释

原文：
{selectedText}";

                var translatedText = await _aiService.GenerateTextAsync(prompt, selectedText.Length * 2, 0.3f);

                // 使用新的翻译预览控件
                DocumentEditorControl.ShowTranslatePreview(selectedText, translatedText, true);
                DocumentEditorControl.HideAIProcessingStatus();
                UpdateStatus("翻译完成，请在预览区域查看结果", true);
            }
            catch (Exception ex)
            {
                DocumentEditorControl.HideAIProcessingStatus();
                _logger.LogError(ex, "翻译文本时发生错误");
                MessageBox.Show($"翻译文本时发生错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 检测文本是否包含中文字符
        /// </summary>
        private bool ContainsChinese(string text)
        {
            foreach (char c in text)
            {
                if (c >= 0x4e00 && c <= 0x9fbb)
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 文本分析
        /// </summary>
        private async void AnalyzeText_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var selectedText = DocumentEditorControl.SelectedText;
                if (string.IsNullOrWhiteSpace(selectedText))
                {
                    MessageBox.Show("请先选择要分析的文本内容。", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                DocumentEditorControl.ShowAIProcessingStatus("正在分析文本...");
                var prompt = $"请对以下文本进行详细分析，包括：1.主题和内容概要 2.写作风格和语言特点 3.情感色彩 4.结构特点 5.改进建议：\n\n{selectedText}";
                var result = await _aiService.GenerateTextAsync(prompt);

                ShowPreviewArea(result, "文本分析");
                DocumentEditorControl.HideAIProcessingStatus();
            }
            catch (Exception ex)
            {
                DocumentEditorControl.HideAIProcessingStatus();
                _logger.LogError(ex, "分析文本时发生错误");
                MessageBox.Show($"分析文本时发生错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 向量搜索
        /// </summary>
        private async void VectorSearch_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var query = Microsoft.VisualBasic.Interaction.InputBox("请输入搜索关键词：", "向量搜索", "");
                if (string.IsNullOrWhiteSpace(query))
                    return;

                DocumentEditorControl.ShowAIProcessingStatus("正在进行向量搜索...");
                var results = await _vectorService.SearchAsync(query, "documents", 5);

                var resultText = "搜索结果：\n\n";
                foreach (var result in results)
                {
                    resultText += $"相似度: {result.Score:F2}\n内容: {result.Content}\n\n";
                }

                ShowPreviewArea(resultText, "向量搜索结果");
                DocumentEditorControl.HideAIProcessingStatus();
            }
            catch (Exception ex)
            {
                DocumentEditorControl.HideAIProcessingStatus();
                _logger.LogError(ex, "向量搜索时发生错误");
                MessageBox.Show($"向量搜索时发生错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 文档索引
        /// </summary>
        private async void DocumentIndex_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var content = DocumentEditorControl.Text;
                if (string.IsNullOrWhiteSpace(content))
                {
                    MessageBox.Show("文档内容为空，无法建立索引。", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                DocumentEditorControl.ShowAIProcessingStatus("正在建立文档索引...");
                await _vectorService.AddDocumentAsync(content, "当前文档");

                DocumentEditorControl.HideAIProcessingStatus();
                MessageBox.Show("文档索引建立完成！", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                DocumentEditorControl.HideAIProcessingStatus();
                _logger.LogError(ex, "建立文档索引时发生错误");
                MessageBox.Show($"建立文档索引时发生错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 导出文档
        /// </summary>
        private void ExportDocument_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var saveFileDialog = new Microsoft.Win32.SaveFileDialog
                {
                    Filter = "Word文档 (*.docx)|*.docx|文本文件 (*.txt)|*.txt|Markdown文件 (*.md)|*.md",
                    DefaultExt = ".docx"
                };

                if (saveFileDialog.ShowDialog() == true)
                {
                    var content = DocumentEditorControl.Text;
                    var extension = System.IO.Path.GetExtension(saveFileDialog.FileName).ToLower();

                    switch (extension)
                    {
                        case ".txt":
                        case ".md":
                            System.IO.File.WriteAllText(saveFileDialog.FileName, content);
                            break;
                        case ".docx":
                            // 这里可以实现Word文档导出
                            System.IO.File.WriteAllText(saveFileDialog.FileName.Replace(".docx", ".txt"), content);
                            break;
                    }

                    MessageBox.Show("文档导出成功！", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "导出文档时发生错误");
                MessageBox.Show($"导出文档时发生错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 一键写论文
        /// </summary>
        private void PaperWriting_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                _logger.LogInformation("用户点击了一键写论文按钮");
                UpdateStatus("正在打开论文写作窗口...", true);

                // 检查是否有当前项目
                if (_currentProject == null)
                {
                    var result = MessageBox.Show(
                        "建议先打开一个项目文件夹来保存生成的论文。\n\n是否继续？",
                        "提示",
                        MessageBoxButton.YesNo,
                        MessageBoxImage.Question);

                    if (result != MessageBoxResult.Yes)
                    {
                        UpdateStatus("已取消论文写作", false);
                        return;
                    }
                }

                // 创建论文写作对话框
                var paperWritingDialog = new Views.PaperWritingDialog(_serviceProvider);
                paperWritingDialog.Owner = this;
                paperWritingDialog.CurrentProject = _currentProject;

                // 显示对话框
                paperWritingDialog.ShowDialog();

                UpdateStatus("论文写作窗口已关闭", true);
                _logger.LogInformation("论文写作对话框已关闭");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "打开论文写作窗口时发生错误");
                UpdateStatus("打开论文写作窗口失败", false);
                MessageBox.Show($"打开论文写作窗口时发生错误：{ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 一键写专利交底书
        /// </summary>
        private void PatentDisclosure_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                _logger.LogInformation("用户点击了一键写专利交底书按钮");
                UpdateStatus("正在打开专利交底书写作窗口...", true);

                // 检查是否有当前项目
                if (_currentProject == null)
                {
                    var result = MessageBox.Show(
                        "建议先打开一个项目文件夹来保存生成的专利交底书。\n\n是否继续？",
                        "提示",
                        MessageBoxButton.YesNo,
                        MessageBoxImage.Question);

                    if (result != MessageBoxResult.Yes)
                    {
                        UpdateStatus("已取消专利交底书写作", false);
                        return;
                    }
                }

                // 创建专利交底书写作对话框
                var patentDisclosureDialog = new Views.PatentDisclosureDialog(_serviceProvider);
                patentDisclosureDialog.Owner = this;
                patentDisclosureDialog.CurrentProject = _currentProject;

                // 显示对话框
                patentDisclosureDialog.ShowDialog();

                UpdateStatus("专利交底书写作窗口已关闭", true);
                _logger.LogInformation("专利交底书写作对话框已关闭");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "打开专利交底书写作窗口时发生错误");
                UpdateStatus("打开专利交底书写作窗口失败", false);
                MessageBox.Show($"打开专利交底书写作窗口时发生错误：{ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 一键写SOP（标准作业程序）
        /// </summary>
        private void SOPWriting_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                _logger.LogInformation("用户点击了一键写SOP按钮");
                UpdateStatus("正在打开SOP写作窗口...", true);

                // 检查是否有当前项目
                if (_currentProject == null)
                {
                    var result = MessageBox.Show(
                        "建议先打开一个项目文件夹来保存生成的SOP文档。\n\n是否继续？",
                        "提示",
                        MessageBoxButton.YesNo,
                        MessageBoxImage.Question);

                    if (result != MessageBoxResult.Yes)
                    {
                        UpdateStatus("已取消SOP写作", false);
                        return;
                    }
                }

                // 获取服务实例
                var sopWritingService = _serviceProvider.GetService<ISOPWritingService>();
                var fileFormatService = _serviceProvider.GetService<IFileFormatService>();
                var projectService = _serviceProvider.GetService<IProjectService>();
                var logger = _serviceProvider.GetService<ILogger<Views.SOPWritingDialog>>();

                if (sopWritingService == null || fileFormatService == null || projectService == null || logger == null)
                {
                    throw new InvalidOperationException("无法获取必要的服务实例");
                }

                // 创建SOP写作对话框
                var sopWritingDialog = new Views.SOPWritingDialog(
                    sopWritingService,
                    fileFormatService,
                    projectService,
                    logger);
                sopWritingDialog.Owner = this;

                // 显示对话框
                sopWritingDialog.ShowDialog();

                UpdateStatus("SOP写作窗口已关闭", true);
                _logger.LogInformation("SOP写作对话框已关闭");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "打开SOP写作窗口时发生错误");
                UpdateStatus("打开SOP写作窗口失败", false);
                MessageBox.Show($"打开SOP写作窗口时发生错误：{ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        #endregion

        private void CreativeRequest_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var dialog = new Views.CreativeRequestDialog(App.ServiceProvider);
                dialog.Owner = this;

                if (dialog.ShowDialog() == true && dialog.IsConfirmed && !string.IsNullOrWhiteSpace(dialog.GeneratedContent))
                {
                    // 将生成的内容插入到编辑器中
                    var currentText = DocumentEditorControl.Text;

                    // 在文档末尾插入内容
                    var newText = currentText + "\n\n" + dialog.GeneratedContent + "\n\n";
                    DocumentEditorControl.Text = newText;

                    UpdateStatus("创作内容已插入", true);
                    _logger.LogInformation("按要求创作内容已插入到编辑器");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "按要求创作时发生错误");
                UpdateStatus("创作失败", false);
            }
        }

        /// <summary>
        /// 从光标处智能续写功能
        /// </summary>
        private async void ContinueWriting_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                UpdateStatus("正在分析上下文并续写...", true);
                DocumentEditorControl.ShowAIProcessingStatus("正在分析上下文...");

                // 获取当前文档内容和光标位置
                var fullText = DocumentEditorControl.Text;
                var caretOffset = DocumentEditorControl.TextEditor?.CaretOffset ?? 0;

                if (string.IsNullOrWhiteSpace(fullText))
                {
                    MessageBox.Show("文档为空，请先输入一些内容作为续写的基础", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    UpdateStatus("续写取消", false);
                    DocumentEditorControl.HideAIProcessingStatus();
                    return;
                }

                // 智能分析上下文
                var contextResult = await AnalyzeSmartContextForContinuationAsync(fullText, caretOffset);

                if (string.IsNullOrWhiteSpace(contextResult.PreviousContext))
                {
                    MessageBox.Show("无法获取足够的上下文信息进行续写", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    UpdateStatus("续写取消", false);
                    DocumentEditorControl.HideAIProcessingStatus();
                    return;
                }

                DocumentEditorControl.ShowAIProcessingStatus("正在生成续写内容...");

                // 构建智能续写提示词
                var prompt = await BuildSmartContinuationPromptAsync(contextResult);

                // 获取AI参数
                var temperature = (float)TemperatureSlider.Value;
                var maxTokens = (int)MaxTokensSlider.Value;

                // 调用AI生成续写内容
                var continuationText = await _aiService.GenerateTextAsync(prompt, maxTokens, temperature);

                if (!string.IsNullOrWhiteSpace(continuationText))
                {
                    // 清理续写内容，确保不重复
                    var cleanedText = CleanContinuationText(continuationText, contextResult.LastSentence);

                    // 直接插入到光标位置
                    DocumentEditorControl.TextEditor?.Document.Insert(caretOffset, cleanedText);

                    // 移动光标到新内容的末尾
                    if (DocumentEditorControl.TextEditor != null)
                    {
                        DocumentEditorControl.TextEditor.CaretOffset = caretOffset + cleanedText.Length;
                        DocumentEditorControl.TextEditor.ScrollToLine(
                            DocumentEditorControl.TextEditor.Document.GetLineByOffset(DocumentEditorControl.TextEditor.CaretOffset).LineNumber);
                    }

                    UpdateStatus($"续写完成，已生成 {cleanedText.Length} 个字符的内容", true);
                    _logger.LogInformation($"智能续写完成，生成了 {cleanedText.Length} 个字符的内容");
                }
                else
                {
                    UpdateStatus("续写失败，AI未返回内容", false);
                }

                DocumentEditorControl.HideAIProcessingStatus();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "续写时发生错误");
                UpdateStatus("续写失败", false);
                DocumentEditorControl.HideAIProcessingStatus();
                MessageBox.Show($"续写时发生错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 分析续写的上下文
        /// </summary>
        private (string PreviousContext, string CurrentPosition) AnalyzeContextForContinuation(string fullText, int caretOffset)
        {
            // 获取光标前的文本作为上下文
            var beforeCursor = fullText.Substring(0, caretOffset);
            var afterCursor = fullText.Substring(caretOffset);

            // 获取最近的上下文（最多1000个字符）
            var contextLength = Math.Min(1000, beforeCursor.Length);
            var previousContext = beforeCursor.Length > contextLength
                ? beforeCursor.Substring(beforeCursor.Length - contextLength)
                : beforeCursor;

            // 分析当前位置的情况
            var currentPosition = "文档中间";
            if (caretOffset == 0)
            {
                currentPosition = "文档开头";
            }
            else if (caretOffset >= fullText.Length)
            {
                currentPosition = "文档末尾";
            }
            else if (string.IsNullOrWhiteSpace(afterCursor.Trim()))
            {
                currentPosition = "文档末尾";
            }

            return (previousContext, currentPosition);
        }

        /// <summary>
        /// 构建续写的提示词
        /// </summary>
        private string BuildContinuationPrompt(string previousContext, string currentPosition)
        {
            var prompt = $@"请根据以下上下文内容进行自然的续写。要求：

1. 仔细分析上下文的内容、风格、语调和情节发展
2. 保持与前文的连贯性和一致性
3. 续写内容应该自然流畅，符合前文的写作风格
4. 如果是小说，请注意人物性格、情节发展的连贯性
5. 如果是技术文档，请保持专业性和逻辑性
6. 续写长度适中，大约200-500字
7. 不要重复前文内容，直接从当前位置继续

当前位置：{currentPosition}

上下文内容：
{previousContext}

请从上述内容的结尾处自然地继续写下去：";

            return prompt;
        }

        private async void CheckConsistency_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                UpdateStatus("正在检查一致性...", true);

                var currentText = DocumentEditorControl.Text;

                if (!string.IsNullOrWhiteSpace(currentText))
                {
                    var previousContext = "林晨是一名大学生，性格内向";
                    var result = await _aiService.CheckConsistencyAsync(currentText, previousContext);

                    UpdateStatus($"一致性检查完成: {(result.IsConsistent ? "通过" : "发现问题")}", result.IsConsistent);
                }
                else
                {
                    UpdateStatus("没有内容可检查", false);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "检查一致性时发生错误");
                UpdateStatus("一致性检查失败", false);
            }
        }

        private void ProjectTools_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_currentProject == null)
                {
                    MessageBox.Show("请先打开一个项目", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                var toolsWindow = new ProjectToolsWindow(_serviceProvider, _currentProject.Id);
                toolsWindow.Owner = this;
                toolsWindow.ShowDialog();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "打开项目工具窗口时发生错误");
                UpdateStatus("打开项目工具失败", false);
            }
        }

        private void ThinkingChainTest_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                UpdateStatus("正在运行思维链测试...", true);
                _logger.LogInformation("开始思维链功能测试");

                // var test = new ThinkingChainTest(); // 临时注释掉，类不存在

                // 创建一个新窗口来显示测试结果
                var testWindow = new Window
                {
                    Title = "思维链处理功能测试结果",
                    Width = 800,
                    Height = 600,
                    Owner = this,
                    WindowStartupLocation = WindowStartupLocation.CenterOwner
                };

                var scrollViewer = new ScrollViewer
                {
                    VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
                    HorizontalScrollBarVisibility = ScrollBarVisibility.Auto,
                    Padding = new Thickness(10)
                };

                var textBlock = new TextBlock
                {
                    FontFamily = new System.Windows.Media.FontFamily("Consolas"),
                    FontSize = 12,
                    TextWrapping = TextWrapping.Wrap
                };

                scrollViewer.Content = textBlock;
                testWindow.Content = scrollViewer;

                // 重定向控制台输出到TextBlock
                var originalOut = Console.Out;
                var stringWriter = new StringWriter();
                Console.SetOut(stringWriter);

                try
                {
                    // test.RunAllTests(); // 临时注释掉，类不存在
                    // test.TestContainsThinkingChain(); // 临时注释掉，类不存在
                    stringWriter.WriteLine("ThinkingChainTest类暂时不可用");
                }
                finally
                {
                    Console.SetOut(originalOut);
                }

                textBlock.Text = stringWriter.ToString();
                testWindow.ShowDialog();

                UpdateStatus("思维链测试完成", true);
                _logger.LogInformation("思维链功能测试完成");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "思维链测试时发生错误");
                UpdateStatus("思维链测试失败", false);
                MessageBox.Show($"思维链测试时发生错误：{ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void ThemeConfig_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                UpdateStatus("正在打开主题配置...", true);

                var themeDialog = new Views.ThemeConfigDialog(App.ServiceProvider);
                themeDialog.Owner = this;

                if (themeDialog.ShowDialog() == true && themeDialog.IsApplied)
                {
                    UpdateStatus("主题配置已应用", true);
                    _logger.LogInformation("用户应用了新的主题配置");
                }
                else
                {
                    UpdateStatus("主题配置已取消", false);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "打开主题配置对话框时发生错误");
                UpdateStatus("打开主题配置失败", false);
                MessageHelper.ShowError(
                    "打开主题配置时发生错误。",
                    ex,
                    "错误",
                    this);
            }
        }

        /// <summary>
        /// 文件命名配置菜单点击事件
        /// </summary>
        private void FileNamingConfig_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                UpdateStatus("正在打开文件命名配置...", true);

                var fileNamingDialog = new Views.FileNamingConfigDialog(App.ServiceProvider);
                fileNamingDialog.Owner = this;

                if (fileNamingDialog.ShowDialog() == true && fileNamingDialog.IsApplied)
                {
                    UpdateStatus("文件命名配置已应用", true);
                    _logger.LogInformation("用户应用了新的文件命名配置");
                }
                else
                {
                    UpdateStatus("文件命名配置已取消", false);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "打开文件命名配置对话框时发生错误");
                UpdateStatus("打开文件命名配置失败", false);
                MessageBox.Show($"打开文件命名配置时发生错误：{ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void DarkModeToggle_Checked(object sender, RoutedEventArgs e)
        {
            try
            {
                UpdateStatus("正在切换到暗黑模式...", true);
                await SwitchToDarkModeAsync();

                // 更新图标
                if (DarkModeIcon != null)
                {
                    DarkModeIcon.Kind = MaterialDesignThemes.Wpf.PackIconKind.WeatherSunny;
                    DarkModeToggle.ToolTip = "切换到浅色模式";
                }

                UpdateStatus("已切换到暗黑模式", false);
                _logger.LogInformation("用户切换到暗黑模式");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "切换到暗黑模式时发生错误");
                UpdateStatus("切换暗黑模式失败", false);
                MessageBox.Show($"切换到暗黑模式时发生错误：{ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void DarkModeToggle_Unchecked(object sender, RoutedEventArgs e)
        {
            try
            {
                UpdateStatus("正在切换到浅色模式...", true);
                await SwitchToLightModeAsync();

                // 更新图标
                if (DarkModeIcon != null)
                {
                    DarkModeIcon.Kind = MaterialDesignThemes.Wpf.PackIconKind.WeatherNight;
                    DarkModeToggle.ToolTip = "切换到暗黑模式";
                }

                UpdateStatus("已切换到浅色模式", false);
                _logger.LogInformation("用户切换到浅色模式");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "切换到浅色模式时发生错误");
                UpdateStatus("切换浅色模式失败", false);
                MessageBox.Show($"切换到浅色模式时发生错误：{ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async Task SwitchToDarkModeAsync()
        {
            var themeService = App.ServiceProvider?.GetService<IThemeService>();
            if (themeService != null)
            {
                var darkTheme = new ThemeConfig
                {
                    BaseTheme = "Dark",
                    PrimaryColor = "#2196F3",
                    SecondaryColor = "#03DAC6",
                    AccentColor = "#1976D2"
                };
                await themeService.ApplyThemeAsync(darkTheme);
            }
        }

        private async Task SwitchToLightModeAsync()
        {
            var themeService = App.ServiceProvider?.GetService<IThemeService>();
            if (themeService != null)
            {
                var lightTheme = new ThemeConfig
                {
                    BaseTheme = "Light",
                    PrimaryColor = "#2196F3",
                    SecondaryColor = "#03DAC6",
                    AccentColor = "#1976D2"
                };
                await themeService.ApplyThemeAsync(lightTheme);
            }
        }

        private void InitializeDarkModeToggle()
        {
            try
            {
                var themeService = App.ServiceProvider?.GetService<IThemeService>();
                if (themeService != null)
                {
                    var currentTheme = themeService.GetCurrentTheme();
                    if (currentTheme != null)
                    {
                        var isDarkMode = currentTheme.BaseTheme == "Dark";

                        // 根据当前主题设置切换按钮状态
                        DarkModeToggle.IsChecked = isDarkMode;

                        // 设置正确的图标和提示
                        if (DarkModeIcon != null)
                        {
                            DarkModeIcon.Kind = isDarkMode
                                ? MaterialDesignThemes.Wpf.PackIconKind.WeatherSunny
                                : MaterialDesignThemes.Wpf.PackIconKind.WeatherNight;
                            DarkModeToggle.ToolTip = isDarkMode ? "切换到浅色模式" : "切换到暗黑模式";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "初始化暗黑模式切换按钮状态失败");
            }
        }

        private void DataCleanup_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                UpdateStatus("正在打开数据库清理工具...", true);

                var cleanupDialog = new Views.DataCleanupDialog();
                cleanupDialog.Owner = this;
                cleanupDialog.ShowDialog();

                UpdateStatus("数据库清理工具已关闭", true);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "打开数据库清理工具时发生错误");
                UpdateStatus("打开数据库清理工具失败", false);
                MessageBox.Show($"打开数据库清理工具时发生错误：{ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void Settings_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var settingsDialog = new SettingsDialog(_serviceProvider);
                settingsDialog.Owner = this;
                settingsDialog.ShowDialog();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "打开设置对话框时发生错误");
                UpdateStatus("打开设置失败", false);
            }
        }

        private void FullScreen_Click(object sender, RoutedEventArgs e)
        {
            // 这里可以实现全屏编辑功能
            // 暂时显示一个消息
            UpdateStatus("全屏编辑功能开发中...", true);
        }

        private async void AIModelConfig_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 添加日志记录
                _logger.LogInformation("AI模型配置菜单被点击");
                UpdateStatus("正在打开AI模型配置窗口...", false);

                // 检查ServiceProvider是否可用
                if (App.ServiceProvider == null)
                {
                    _logger.LogError("ServiceProvider为null");
                    UpdateStatus("服务提供程序未初始化", true);
                    MessageBox.Show("服务提供程序未初始化，请重启应用程序。", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                // 在UI线程创建配置窗口
                Views.AIModelConfigWindow? configWindow = null;

                try
                {
                    _logger.LogInformation("正在创建AI模型配置窗口");
                    configWindow = new Views.AIModelConfigWindow(App.ServiceProvider);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "创建AI配置窗口失败");
                    UpdateStatus($"创建配置窗口失败: {ex.Message}", true);
                    MessageBox.Show($"创建配置窗口失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                // 设置窗口所有者并显示
                configWindow.Owner = this;
                _logger.LogInformation("显示AI模型配置窗口");
                UpdateStatus("AI模型配置窗口已打开", false);

                var result = configWindow.ShowDialog();
                _logger.LogInformation($"配置窗口关闭，结果: {result}");

                if (result == true && configWindow.Result != null)
                {
                    UpdateStatus("正在保存配置...", false);
                    _logger.LogInformation("开始保存配置");

                    // 保存配置
                    var configService = App.ServiceProvider.GetRequiredService<IAIModelConfigService>();
                    await configService.SaveConfigAsync(configWindow.Result);

                    // 重新加载AI服务配置
                    UpdateStatus("正在重新加载AI服务...", false);
                    if (_aiService is AIServiceManager aiServiceManager)
                    {
                        await aiServiceManager.ReloadConfigurationAsync();
                        _logger.LogInformation("AI服务配置已重新加载");
                    }

                    // 重新加载ViewModel中的AI模型列表
                    UpdateStatus("正在更新模型列表...", false);
                    if (_viewModel != null)
                    {
                        await _viewModel.RefreshAIModelsAsync();
                        _logger.LogInformation("ViewModel AI模型列表已更新");
                    }

                    // 等待AI服务完全初始化
                    await Task.Delay(2000);

                    // 更新状态栏的AI模型信息
                    UpdateStatus("正在更新状态栏...", false);
                    await UpdateAIModelStatusAsync();
                    _logger.LogInformation("状态栏AI模型信息已更新");

                    UpdateStatus("AI模型配置已保存", false);
                    _logger.LogInformation("配置保存完成");
                }
                else
                {
                    UpdateStatus("配置已取消", false);
                    _logger.LogInformation("用户取消了配置");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "打开AI模型配置窗口失败");
                UpdateStatus($"配置失败: {ex.Message}", true);

                // 显示详细错误信息
                var errorMessage = $"打开AI模型配置窗口时发生错误：\n\n{ex.Message}";
                if (ex.InnerException != null)
                {
                    errorMessage += $"\n\n内部错误：{ex.InnerException.Message}";
                }
                errorMessage += $"\n\n堆栈跟踪：\n{ex.StackTrace}";
                MessageBox.Show(errorMessage, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void VectorModelConfig_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 添加日志记录
                _logger.LogInformation("向量模型配置菜单被点击");
                UpdateStatus("正在打开向量模型配置窗口...", false);

                // 检查ServiceProvider是否可用
                if (App.ServiceProvider == null)
                {
                    _logger.LogError("ServiceProvider为null");
                    UpdateStatus("服务提供程序未初始化", true);
                    MessageBox.Show("服务提供程序未初始化，请重启应用程序。", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                // 在UI线程创建配置窗口
                Views.VectorModelConfigWindow? configWindow = null;

                try
                {
                    _logger.LogInformation("正在创建向量模型配置窗口");
                    configWindow = new Views.VectorModelConfigWindow(App.ServiceProvider);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "创建向量模型配置窗口失败");
                    UpdateStatus($"创建配置窗口失败: {ex.Message}", true);
                    MessageBox.Show($"创建配置窗口失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                // 设置窗口所有者并显示
                configWindow.Owner = this;
                _logger.LogInformation("显示向量模型配置窗口");
                UpdateStatus("向量模型配置窗口已打开", false);

                var result = configWindow.ShowDialog();
                _logger.LogInformation($"向量模型配置窗口关闭，结果: {result}");

                if (result == true && configWindow.Result != null)
                {
                    UpdateStatus("正在保存向量模型配置...", false);
                    _logger.LogInformation("开始保存向量模型配置");

                    // 保存配置
                    var configService = App.ServiceProvider.GetRequiredService<IVectorModelConfigService>();
                    await configService.SaveConfigAsync(configWindow.Result);

                    UpdateStatus("向量模型配置已保存", false);
                    _logger.LogInformation("向量模型配置保存完成");

                    // 显示成功消息
                    MessageBox.Show("向量模型配置已成功保存！", "配置成功", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                else
                {
                    UpdateStatus("向量模型配置已取消", false);
                    _logger.LogInformation("用户取消了向量模型配置");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "打开向量模型配置窗口失败");
                UpdateStatus($"向量模型配置失败: {ex.Message}", true);

                // 显示详细错误信息
                var errorMessage = $"打开向量模型配置窗口时发生错误：\n\n{ex.Message}";
                if (ex.InnerException != null)
                {
                    errorMessage += $"\n\n内部错误：{ex.InnerException.Message}";
                }
                errorMessage += $"\n\n堆栈跟踪：\n{ex.StackTrace}";
                MessageBox.Show(errorMessage, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void NewProject_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var dialog = new Views.NewProjectDialog();
                dialog.Owner = this;
                if (dialog.ShowDialog() == true && dialog.IsConfirmed)
                {
                    UpdateStatus("正在创建新项目...", true);

                    var project = await _projectService.CreateProjectAsync(
                        dialog.ProjectName,
                        dialog.ProjectType,
                        dialog.ProjectPath,
                        dialog.ProjectDescription);

                    UpdateStatus("项目创建成功", true);
                    _logger.LogInformation($"创建新项目: {dialog.ProjectName}");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建项目时发生错误");
                UpdateStatus("项目创建失败", false);
            }
        }

        private void OpenProject_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                UpdateStatus("打开项目功能开发中...", true);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "打开项目时发生错误");
                UpdateStatus("项目打开失败", false);
            }
        }

        private async void SaveDocument_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_viewModel?.CurrentDocumentPath == null)
                {
                    UpdateStatus("没有打开的文档可保存", false);
                    return;
                }

                UpdateStatus("正在保存文档...", true);

                var content = DocumentEditorControl.Text;
                var filePath = _viewModel.CurrentDocumentPath;
                var extension = Path.GetExtension(filePath).ToLower();

                switch (extension)
                {
                    case ".docx":
                        SaveDocxFile(filePath, content);
                        break;
                    case ".txt":
                    case ".md":
                        await File.WriteAllTextAsync(filePath, content);
                        break;
                    default:
                        await File.WriteAllTextAsync(filePath, content);
                        break;
                }

                UpdateStatus($"文档已保存: {Path.GetFileName(filePath)}", true);
                _logger.LogInformation($"成功保存文档: {filePath}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存文档时发生错误");
                UpdateStatus($"文档保存失败: {ex.Message}", false);
                MessageBox.Show($"保存文档失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void SaveDocxFile(string filePath, string content)
        {
            try
            {
                // 创建备份
                var backupPath = filePath + ".backup";
                if (File.Exists(filePath))
                {
                    File.Copy(filePath, backupPath, true);
                }

                using var document = WordprocessingDocument.Create(filePath, DocumentFormat.OpenXml.WordprocessingDocumentType.Document, true);

                // 添加主文档部分
                var mainPart = document.AddMainDocumentPart();
                mainPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document();
                var body = mainPart.Document.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Body());

                // 将文本内容按行分割并添加为段落
                var lines = content.Split(new[] { '\r', '\n' }, StringSplitOptions.None);
                foreach (var line in lines)
                {
                    var paragraph = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
                    var run = new DocumentFormat.OpenXml.Wordprocessing.Run();
                    var text = new DocumentFormat.OpenXml.Wordprocessing.Text(line);
                    run.Append(text);
                    paragraph.Append(run);
                    body.Append(paragraph);
                }

                // 删除备份文件
                if (File.Exists(backupPath))
                {
                    File.Delete(backupPath);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"保存docx文件失败: {filePath}");

                // 恢复备份
                var backupPath = filePath + ".backup";
                if (File.Exists(backupPath))
                {
                    File.Copy(backupPath, filePath, true);
                    File.Delete(backupPath);
                }

                throw new InvalidOperationException($"无法保存Word文档：{ex.Message}", ex);
            }
        }

        // 添加一些基本的事件处理方法
        private async void OpenProjectFolder_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var folderDialog = new Microsoft.Win32.OpenFolderDialog
                {
                    Title = "选择项目文件夹",
                    Multiselect = false
                };

                if (folderDialog.ShowDialog() == true)
                {
                    var selectedPath = folderDialog.FolderName;
                    var projectName = Path.GetFileName(selectedPath);
                    UpdateStatus($"正在打开项目文件夹: {selectedPath}", true);

                    // 添加到项目历史记录
                    await _historyService.AddOrUpdateHistoryAsync(selectedPath, projectName, "Normal");

                    // 创建或加载项目
                    _currentProject = new Project
                    {
                        Id = 1, // 临时ID
                        Name = projectName,
                        RootPath = selectedPath,
                        Type = "Normal",
                        CreatedAt = DateTime.Now,
                        UpdatedAt = DateTime.Now
                    };

                    // 加载项目文件夹内容
                    LoadProjectFolder(selectedPath);

                    // 刷新历史列表
                    await LoadHistoryProjectsAsync();

                    // 更新项目信息显示
                    UpdateProjectInfoDisplay();

                    UpdateStatus("项目文件夹已打开", true);
                    _logger.LogInformation($"打开项目文件夹: {selectedPath}");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "打开项目文件夹时发生错误");
                UpdateStatus("打开项目文件夹失败", false);
                MessageBox.Show($"打开项目失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void TestAIConnection_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                UpdateStatus("正在测试AI连接...", true);
                _logger.LogInformation("开始AI连接测试");

                // 获取当前AI模型配置
                var configService = App.ServiceProvider.GetRequiredService<IAIModelConfigService>();
                var config = await configService.GetConfigAsync();

                // 获取当前模型信息
                var currentModel = _aiService?.GetCurrentModel();
                var platformName = config.Platform ?? "未知平台";
                var modelName = currentModel?.Name ?? "未选择模型";

                UpdateStatus($"正在测试 {platformName} - {modelName} 连接...", true);

                // 执行连接测试
                await configService.TestConnectionAsync(config);

                // 测试成功
                UpdateStatus($"{platformName} - {modelName} 连接测试成功", false);
                _logger.LogInformation($"AI连接测试成功: {platformName} - {modelName}");

                // 显示成功消息
                MessageBox.Show(
                    $"AI模型连接测试成功！\n\n平台: {platformName}\n模型: {modelName}",
                    "连接测试",
                    MessageBoxButton.OK,
                    MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "AI连接测试失败");
                UpdateStatus($"AI连接测试失败: {ex.Message}", false);

                // 显示错误消息
                MessageBox.Show(
                    $"AI模型连接测试失败！\n\n错误信息: {ex.Message}\n\n请检查AI模型配置是否正确。",
                    "连接测试失败",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error);
            }
        }

        private async void CreateDocxFile_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 创建文档创建对话框
                var createDocDialog = new Views.CreateDocumentDialog
                {
                    Owner = this
                };

                // 如果当前有选中的项目，设置默认路径
                if (_currentProject != null)
                {
                    createDocDialog.DefaultPath = _currentProject.RootPath;
                }

                if (createDocDialog.ShowDialog() != true)
                {
                    UpdateStatus("取消创建文档", false);
                    return;
                }

                var fileName = createDocDialog.DocumentName;
                var targetPath = createDocDialog.SelectedPath;

                // 确保文件名有.docx扩展名
                if (!fileName.EndsWith(".docx", StringComparison.OrdinalIgnoreCase))
                {
                    fileName += ".docx";
                }

                var fullPath = Path.Combine(targetPath, fileName);

                // 检查文件是否已存在
                if (File.Exists(fullPath))
                {
                    var result = MessageBox.Show(
                        $"文件 '{fileName}' 已存在，是否覆盖？",
                        "文件已存在",
                        MessageBoxButton.YesNo,
                        MessageBoxImage.Question);

                    if (result != MessageBoxResult.Yes)
                    {
                        return;
                    }
                }

                // 创建docx文件
                await CreateDocxFileAsync(fullPath, "");

                // 刷新项目导航
                if (_currentProject != null)
                {
                    await RefreshProjectNavigation();
                }

                UpdateStatus($"文档已创建: {fileName}", true);
                _logger.LogInformation($"成功创建docx文档: {fullPath}");

                // 自动打开新创建的文档
                await DocumentEditorControl.LoadDocumentAsync(fullPath);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建docx文件时发生错误");
                UpdateStatus("创建docx文件失败", false);
                MessageBox.Show($"创建docx文件失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void RefreshProject_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                UpdateStatus("正在刷新项目...", true);
                await RefreshProjectNavigation();
                UpdateStatus("项目刷新完成", true);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "刷新项目时发生错误");
                UpdateStatus("项目刷新失败", false);
            }
        }

        /// <summary>
        /// 一键转换.txt到.md功能
        /// </summary>
        private async void ConvertTxtToMd_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 检查是否有当前项目
                if (_currentProject == null)
                {
                    MessageBox.Show("请先打开一个项目才能进行转换。", "提示",
                        MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                // 确认转换操作
                var result = MessageBox.Show(
                    $"将要创建一个新的MD项目：{_currentProject.Name}.MD\n" +
                    $"原项目路径：{_currentProject.RootPath}\n" +
                    $"新项目路径：{_currentProject.RootPath}.MD\n\n" +
                    "所有.txt文件将被转换为.md文件，其他文件保持不变。\n" +
                    "是否继续？",
                    "确认转换",
                    MessageBoxButton.YesNo,
                    MessageBoxImage.Question);

                if (result != MessageBoxResult.Yes)
                {
                    return;
                }

                UpdateStatus("正在转换项目...", true);
                _logger.LogInformation($"开始转换项目: {_currentProject.Name}");

                await ConvertProjectTxtToMdAsync(_currentProject);

                UpdateStatus("项目转换完成", true);
                MessageBox.Show("项目转换完成！新的MD项目已创建。", "转换完成",
                    MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "转换项目时发生错误");
                UpdateStatus("项目转换失败", false);
                MessageBox.Show($"转换项目时发生错误：{ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 转换项目中的.txt文件到.md文件
        /// </summary>
        private async Task ConvertProjectTxtToMdAsync(Project sourceProject)
        {
            try
            {
                var sourceDir = sourceProject.RootPath;
                var targetDir = sourceDir + ".MD";

                _logger.LogInformation($"开始转换项目: {sourceDir} -> {targetDir}");

                // 检查源目录是否存在
                if (!Directory.Exists(sourceDir))
                {
                    throw new DirectoryNotFoundException($"源项目目录不存在: {sourceDir}");
                }

                // 如果目标目录已存在，询问是否覆盖
                if (Directory.Exists(targetDir))
                {
                    var overwriteResult = MessageBox.Show(
                        $"目标目录已存在：{targetDir}\n是否覆盖？",
                        "目录已存在",
                        MessageBoxButton.YesNo,
                        MessageBoxImage.Warning);

                    if (overwriteResult != MessageBoxResult.Yes)
                    {
                        return;
                    }

                    // 删除现有目录
                    Directory.Delete(targetDir, true);
                }

                // 创建目标目录
                Directory.CreateDirectory(targetDir);

                // 递归复制并转换文件
                await CopyAndConvertDirectoryAsync(sourceDir, targetDir);

                _logger.LogInformation($"项目转换完成: {targetDir}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"转换项目失败: {sourceProject.Name}");
                throw;
            }
        }

        /// <summary>
        /// 递归复制目录并转换.txt文件为.md文件
        /// </summary>
        private async Task CopyAndConvertDirectoryAsync(string sourceDir, string targetDir)
        {
            try
            {
                // 确保目标目录存在
                Directory.CreateDirectory(targetDir);

                // 复制所有文件
                var files = Directory.GetFiles(sourceDir);
                foreach (var file in files)
                {
                    var fileName = Path.GetFileName(file);
                    var fileExtension = Path.GetExtension(file).ToLower();

                    string targetFile;

                    if (fileExtension == ".txt")
                    {
                        // 将.txt文件转换为.md文件
                        var nameWithoutExtension = Path.GetFileNameWithoutExtension(file);
                        targetFile = Path.Combine(targetDir, nameWithoutExtension + ".md");

                        _logger.LogDebug($"转换文件: {file} -> {targetFile}");

                        // 读取原文件内容并写入新文件
                        var content = await File.ReadAllTextAsync(file, System.Text.Encoding.UTF8);
                        await File.WriteAllTextAsync(targetFile, content, System.Text.Encoding.UTF8);
                    }
                    else
                    {
                        // 其他文件直接复制
                        targetFile = Path.Combine(targetDir, fileName);

                        _logger.LogDebug($"复制文件: {file} -> {targetFile}");
                        File.Copy(file, targetFile, true);
                    }
                }

                // 递归处理子目录
                var directories = Directory.GetDirectories(sourceDir);
                foreach (var directory in directories)
                {
                    var dirName = Path.GetFileName(directory);
                    var targetSubDir = Path.Combine(targetDir, dirName);

                    await CopyAndConvertDirectoryAsync(directory, targetSubDir);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"复制目录失败: {sourceDir} -> {targetDir}");
                throw;
            }
        }

        private async Task RefreshProjectNavigation()
        {
            try
            {
                _logger.LogInformation($"RefreshProjectNavigation开始 - 当前项目: {(_currentProject != null ? $"{_currentProject.Name} ({_currentProject.RootPath})" : "null")}");

                if (_currentProject != null)
                {
                    // 如果有当前项目，重新加载当前项目的文件夹内容，而不是刷新整个项目列表
                    _logger.LogInformation($"重新加载当前项目文件夹: {_currentProject.RootPath}");
                    LoadProjectFolder(_currentProject.RootPath);
                }
                else if (_viewModel != null)
                {
                    // 如果没有当前项目，才刷新项目列表
                    _logger.LogInformation("没有当前项目，刷新项目列表");
                    await _viewModel.RefreshProjectsAsync();
                }

                _logger.LogInformation($"RefreshProjectNavigation完成 - 当前项目: {(_currentProject != null ? $"{_currentProject.Name} ({_currentProject.RootPath})" : "null")}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "刷新项目导航时发生错误");
                throw;
            }
        }

        /// <summary>
        /// 创建docx文件
        /// </summary>
        private async Task CreateDocxFileAsync(string filePath, string content)
        {
            await Task.Run(() =>
            {
                // 确保目录存在
                var directory = Path.GetDirectoryName(filePath);
                if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                using var document = WordprocessingDocument.Create(filePath, DocumentFormat.OpenXml.WordprocessingDocumentType.Document, true);

                // 添加主文档部分
                var mainPart = document.AddMainDocumentPart();
                mainPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document();
                var body = mainPart.Document.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Body());

                // 将文本内容按行分割并添加为段落
                var lines = content.Split(new[] { '\r', '\n' }, StringSplitOptions.None);
                foreach (var line in lines)
                {
                    var paragraph = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
                    var run = new DocumentFormat.OpenXml.Wordprocessing.Run();
                    var text = new DocumentFormat.OpenXml.Wordprocessing.Text(line);
                    run.Append(text);
                    paragraph.Append(run);
                    body.Append(paragraph);
                }
            });
        }

        private void LoadProjectFolder(string folderPath)
        {
            try
            {
                // 验证文件夹路径是否有效
                if (string.IsNullOrEmpty(folderPath) || !Directory.Exists(folderPath))
                {
                    _logger.LogWarning($"项目文件夹路径无效: {folderPath}");
                    UpdateStatus("项目文件夹路径无效", false);
                    return;
                }

                // 更新状态显示当前文件夹
                if (_viewModel != null)
                {
                    _viewModel.CurrentProjectName = $"文件夹: {Path.GetFileName(folderPath)}";

                    // 清空当前项目树
                    _viewModel.ProjectItems.Clear();

                    // 扫描文件夹中的文档文件
                    ScanFolderFiles(folderPath);
                }

                // 设置文档编辑器的当前项目路径
                DocumentEditorControl.CurrentProjectPath = folderPath;

                // 更新文档编辑器的项目信息
                DocumentEditorControl?.UpdateDocumentStatus($"当前项目: {Path.GetFileName(folderPath)}");

                _logger.LogInformation($"项目文件夹加载完成: {folderPath}");
                UpdateStatus($"已加载项目文件夹: {Path.GetFileName(folderPath)}", true);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "加载项目文件夹时发生错误");
                UpdateStatus("加载项目文件夹失败", false);
            }
        }

        private void ScanFolderFiles(string folderPath)
        {
            try
            {
                // 支持的文档文件扩展名
                var supportedExtensions = new[] { ".docx", ".doc", ".txt", ".md" };

                // 创建文件夹根节点
                var folderItem = new ViewModels.ProjectTreeItem
                {
                    Name = Path.GetFileName(folderPath),
                    Type = ViewModels.ProjectTreeItemType.Project,
                    FilePath = folderPath,
                    Children = new System.Collections.ObjectModel.ObservableCollection<ViewModels.ProjectTreeItem>()
                };

                // 递归扫描文件夹结构
                ScanFolderRecursive(folderPath, folderItem, supportedExtensions);

                // 只有当文件夹有内容时才添加到项目树
                if (folderItem.Children.Any())
                {
                    _viewModel?.ProjectItems.Add(folderItem);
                    var totalFiles = CountFilesRecursive(folderItem);
                    _logger.LogInformation($"扫描到 {totalFiles} 个文档文件");
                }
                else
                {
                    _logger.LogInformation("文件夹中没有找到支持的文档文件");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "扫描文件夹文件时发生错误");
                throw;
            }
        }

        private void ScanFolderRecursive(string folderPath, ViewModels.ProjectTreeItem parentItem, string[] supportedExtensions)
        {
            try
            {
                // 获取当前文件夹中的文件
                var files = Directory.GetFiles(folderPath)
                    .Where(file => supportedExtensions.Contains(Path.GetExtension(file).ToLower()))
                    .OrderBy(file => Path.GetFileName(file))
                    .ToList();

                // 添加文件到当前节点
                foreach (var file in files)
                {
                    var fileItem = new ViewModels.ProjectTreeItem
                    {
                        Name = Path.GetFileName(file),
                        Type = ViewModels.ProjectTreeItemType.Document,
                        FilePath = file
                    };
                    parentItem.Children.Add(fileItem);
                }

                // 获取子文件夹
                var subFolders = Directory.GetDirectories(folderPath)
                    .Where(dir => !Path.GetFileName(dir).StartsWith(".")) // 排除隐藏文件夹
                    .OrderBy(dir => Path.GetFileName(dir))
                    .ToList();

                // 处理子文件夹 - 使用懒加载模式
                foreach (var subFolder in subFolders)
                {
                    var subFolderItem = new ViewModels.ProjectTreeItem
                    {
                        Name = Path.GetFileName(subFolder),
                        Type = ViewModels.ProjectTreeItemType.Project,
                        FilePath = subFolder,
                        Children = new System.Collections.ObjectModel.ObservableCollection<ViewModels.ProjectTreeItem>()
                    };

                    // 检查子文件夹是否有内容，如果有则添加占位符用于懒加载
                    if (HasSupportedFiles(subFolder, supportedExtensions))
                    {
                        // 添加占位符，表示有子项但未加载
                        subFolderItem.Children.Add(new ViewModels.ProjectTreeItem
                        {
                            Name = "加载中...",
                            Type = ViewModels.ProjectTreeItemType.Document
                        });
                        parentItem.Children.Add(subFolderItem);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning($"扫描文件夹时发生错误: {folderPath}, {ex.Message}");
            }
        }

        /// <summary>
        /// 懒加载文件夹子项
        /// </summary>
        private void LoadFolderChildrenLazy(ViewModels.ProjectTreeItem folderItem)
        {
            try
            {
                if (string.IsNullOrEmpty(folderItem.FilePath) || !Directory.Exists(folderItem.FilePath))
                    return;

                // 检查是否有占位符，如果有则清除
                if (folderItem.Children != null && folderItem.Children.Any(c => c.Name == "加载中..."))
                {
                    folderItem.Children.Clear();
                }
                // 如果已经加载过真实子项，不重复加载
                else if (folderItem.Children != null && folderItem.Children.Any())
                {
                    return;
                }

                // 初始化Children集合
                if (folderItem.Children == null)
                {
                    folderItem.Children = new System.Collections.ObjectModel.ObservableCollection<ViewModels.ProjectTreeItem>();
                }

                var supportedExtensions = new[] { ".docx", ".doc", ".txt", ".md" };

                // 扫描文件
                var files = Directory.GetFiles(folderItem.FilePath)
                    .Where(file => supportedExtensions.Contains(Path.GetExtension(file).ToLower()))
                    .OrderBy(file => Path.GetFileName(file))
                    .ToList();

                foreach (var file in files)
                {
                    var fileItem = new ViewModels.ProjectTreeItem
                    {
                        Name = Path.GetFileName(file),
                        Type = ViewModels.ProjectTreeItemType.Document,
                        FilePath = file
                    };
                    folderItem.Children.Add(fileItem);
                }

                // 扫描子文件夹
                var subFolders = Directory.GetDirectories(folderItem.FilePath)
                    .Where(dir => !Path.GetFileName(dir).StartsWith(".")) // 排除隐藏文件夹
                    .OrderBy(dir => Path.GetFileName(dir))
                    .ToList();

                foreach (var subFolder in subFolders)
                {
                    var subFolderItem = new ViewModels.ProjectTreeItem
                    {
                        Name = Path.GetFileName(subFolder),
                        Type = ViewModels.ProjectTreeItemType.Project,
                        FilePath = subFolder,
                        Children = new System.Collections.ObjectModel.ObservableCollection<ViewModels.ProjectTreeItem>()
                    };

                    // 检查子文件夹是否有内容，如果有则添加占位符
                    if (HasSupportedFiles(subFolder, supportedExtensions))
                    {
                        // 添加占位符，表示有子项但未加载
                        subFolderItem.Children.Add(new ViewModels.ProjectTreeItem
                        {
                            Name = "加载中...",
                            Type = ViewModels.ProjectTreeItemType.Document
                        });
                        folderItem.Children.Add(subFolderItem);
                    }
                }

                _logger.LogInformation($"懒加载完成: {folderItem.Name}, 子项数量: {folderItem.Children.Count}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"懒加载文件夹子项失败: {folderItem.Name}");
            }
        }

        /// <summary>
        /// 检查文件夹是否包含支持的文件
        /// </summary>
        private bool HasSupportedFiles(string folderPath, string[] supportedExtensions)
        {
            try
            {
                // 检查当前文件夹是否有支持的文件
                var hasFiles = Directory.GetFiles(folderPath)
                    .Any(file => supportedExtensions.Contains(Path.GetExtension(file).ToLower()));

                if (hasFiles)
                    return true;

                // 检查子文件夹是否有支持的文件
                var subFolders = Directory.GetDirectories(folderPath)
                    .Where(dir => !Path.GetFileName(dir).StartsWith("."));

                foreach (var subFolder in subFolders)
                {
                    if (HasSupportedFiles(subFolder, supportedExtensions))
                        return true;
                }

                return false;
            }
            catch
            {
                return false;
            }
        }

        private int CountFilesRecursive(ViewModels.ProjectTreeItem item)
        {
            int count = 0;
            foreach (var child in item.Children)
            {
                if (child.Type == ViewModels.ProjectTreeItemType.Document)
                {
                    count++;
                }
                else if (child.Type == ViewModels.ProjectTreeItemType.Project)
                {
                    count += CountFilesRecursive(child);
                }
            }
            return count;
        }

        /// <summary>
        /// 进入项目文件夹
        /// </summary>
        private async Task EnterProjectFolderAsync(ViewModels.ProjectTreeItem folderItem)
        {
            try
            {
                var folderPath = folderItem.FilePath;
                if (string.IsNullOrEmpty(folderPath) || !Directory.Exists(folderPath))
                {
                    UpdateStatus("文件夹路径无效", false);
                    return;
                }

                UpdateStatus($"正在进入文件夹: {folderItem.Name}", true);

                // 添加到历史记录
                await _historyService.AddOrUpdateHistoryAsync(folderPath, folderItem.Name, "Normal");

                // 创建新的项目对象
                _currentProject = new Project
                {
                    Id = 1, // 临时ID
                    Name = folderItem.Name,
                    RootPath = folderPath,
                    Type = "Normal",
                    CreatedAt = DateTime.Now,
                    UpdatedAt = DateTime.Now
                };

                _logger.LogInformation($"已设置当前项目: {_currentProject.Name}, 路径: {_currentProject.RootPath}");

                // 加载文件夹内容
                LoadProjectFolder(folderPath);

                // 刷新历史列表
                await LoadHistoryProjectsAsync();

                // 更新项目信息显示
                UpdateProjectInfoDisplay();

                UpdateStatus($"已进入文件夹: {folderItem.Name}", true);
                _logger.LogInformation($"进入项目文件夹完成: {folderPath}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"进入项目文件夹失败: {folderItem.Name}");
                UpdateStatus("进入文件夹失败", false);
                MessageBox.Show($"进入文件夹失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async Task LoadHistoryProjectsAsync()
        {
            try
            {
                // 先清理无效的历史记录
                var cleanedCount = await _historyService.CleanupInvalidHistoryAsync();
                if (cleanedCount > 0)
                {
                    _logger.LogInformation($"自动清理了 {cleanedCount} 个无效的历史记录");
                }

                // 清理重复的历史记录
                var duplicateCount = await _historyService.CleanupDuplicateHistoryAsync();
                if (duplicateCount > 0)
                {
                    _logger.LogInformation($"自动清理了 {duplicateCount} 个重复的历史记录");
                }

                // 使用历史服务加载项目历史
                var historyProjects = await _historyService.GetAllHistoryAsync();
                HistoryProjectListBox.ItemsSource = historyProjects;
                _logger.LogInformation($"加载了 {historyProjects.Count} 个历史项目");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "加载历史项目时发生错误");
                // 如果加载失败，使用空列表
                HistoryProjectListBox.ItemsSource = new List<object>();
            }
        }

        private async void CreateProjectFolder_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 检查是否按住Ctrl键，如果是则创建简单文件夹
                if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
                {
                    await CreateSimpleFolderAsync();
                    return;
                }

                // 使用正式的创建项目对话框
                var createDialog = new Views.CreateProjectDialog
                {
                    Owner = this
                };

                if (createDialog.ShowDialog() != true)
                {
                    UpdateStatus("取消创建项目文件夹", false);
                    return;
                }

                var folderName = createDialog.ProjectName;
                var projectType = createDialog.ProjectType;
                var basePath = createDialog.ProjectPath;
                var description = createDialog.ProjectDescription;

                // 构建完整的项目路径
                var projectFolderPath = Path.Combine(basePath, folderName);

                // 检查文件夹是否已存在
                if (Directory.Exists(projectFolderPath))
                {
                    var result = MessageBox.Show(
                        $"文件夹 '{folderName}' 已存在，是否要将其导入为项目？",
                        "文件夹已存在",
                        MessageBoxButton.YesNo,
                        MessageBoxImage.Question);

                    if (result == MessageBoxResult.Yes)
                    {
                        // 检查数据库连接
                        try
                        {
                            var projectService = App.ServiceProvider.GetRequiredService<Services.IProjectService>();

                            // 先测试数据库连接
                            var testProjects = await projectService.GetAllProjectsAsync();
                            _logger.LogInformation($"数据库连接正常，当前有 {testProjects.Count} 个项目");

                            var existingProject = await projectService.GetProjectByPathAsync(projectFolderPath);

                            if (existingProject == null)
                            {
                                // 验证项目名称和路径
                                if (string.IsNullOrWhiteSpace(folderName) || folderName.Length > 200)
                                {
                                    MessageBox.Show("项目名称无效或过长（最大200字符）", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                                    return;
                                }

                                if (projectFolderPath.Length > 500)
                                {
                                    MessageBox.Show("项目路径过长（最大500字符）", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                                    return;
                                }

                                // 导入为新项目
                                var project = await projectService.CreateProjectAsync(
                                    folderName,
                                    "Normal",
                                    projectFolderPath,
                                    $"从现有文件夹导入的项目: {projectFolderPath}");

                                // 刷新项目导航
                                if (_viewModel != null)
                                {
                                    await _viewModel.RefreshProjectsAsync();
                                }

                                UpdateStatus($"项目文件夹已导入: {folderName}", true);
                                _logger.LogInformation($"成功导入项目文件夹: {projectFolderPath}");
                            }
                            else
                            {
                                MessageBox.Show("该文件夹已经是一个项目", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                            }
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError(ex, "导入项目文件夹时发生错误");
                            MessageBox.Show($"导入项目文件夹失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                }
                else
                {
                    // 创建新的项目文件夹
                    Directory.CreateDirectory(projectFolderPath);

                    // 创建项目记录
                    var projectService = App.ServiceProvider.GetRequiredService<Services.IProjectService>();
                    var project = await projectService.CreateProjectAsync(
                        folderName,
                        projectType,
                        projectFolderPath,
                        description);

                    // 刷新项目导航
                    if (_viewModel != null)
                    {
                        await _viewModel.RefreshProjectsAsync();
                    }

                    UpdateStatus($"项目文件夹已创建: {folderName}", true);
                    _logger.LogInformation($"成功创建项目文件夹: {projectFolderPath}");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建项目文件夹时发生错误");
                UpdateStatus("创建项目文件夹失败", false);
                MessageBox.Show($"创建项目文件夹失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async Task CreateSimpleFolderAsync()
        {
            try
            {
                // 创建文件夹创建对话框
                var createFolderDialog = new Views.CreateFolderDialog
                {
                    Owner = this
                };

                // 如果当前有选中的项目，设置默认路径
                if (_currentProject != null)
                {
                    createFolderDialog.DefaultPath = _currentProject.RootPath;
                }

                if (createFolderDialog.ShowDialog() != true)
                {
                    UpdateStatus("取消创建文件夹", false);
                    return;
                }

                var folderName = createFolderDialog.FolderName;
                var targetPath = createFolderDialog.SelectedPath;
                var fullPath = Path.Combine(targetPath, folderName);

                // 检查文件夹是否已存在
                if (Directory.Exists(fullPath))
                {
                    var result = MessageBox.Show(
                        $"文件夹 '{folderName}' 已存在，是否继续？",
                        "文件夹已存在",
                        MessageBoxButton.YesNo,
                        MessageBoxImage.Question);

                    if (result != MessageBoxResult.Yes)
                    {
                        return;
                    }
                }
                else
                {
                    // 创建文件夹
                    Directory.CreateDirectory(fullPath);
                }

                // 添加到项目历史记录
                await _historyService.AddOrUpdateHistoryAsync(fullPath, folderName, "Normal");

                // 刷新项目导航
                if (_viewModel != null)
                {
                    await _viewModel.RefreshProjectsAsync();
                }

                // 刷新历史项目列表
                await LoadHistoryProjectsAsync();

                UpdateStatus($"文件夹创建成功: {folderName}", true);
                _logger.LogInformation($"创建文件夹: {fullPath}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建文件夹时发生错误");
                UpdateStatus("创建文件夹失败", false);
                MessageBox.Show($"创建文件夹失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        // 基本的事件处理方法
        private async void ProjectTreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            try
            {
                if (e.NewValue is ViewModels.ProjectTreeItem selectedItem)
                {
                    // 如果选中的是文档，预览文档内容
                    if (selectedItem.Type == ViewModels.ProjectTreeItemType.Document &&
                        !string.IsNullOrEmpty(selectedItem.FilePath) &&
                        File.Exists(selectedItem.FilePath))
                    {
                        await DocumentEditorControl.LoadDocumentAsync(selectedItem.FilePath);
                        UpdateStatus($"已加载文档: {selectedItem.Name}", true);
                    }
                    else if (selectedItem.Type == ViewModels.ProjectTreeItemType.Project)
                    {
                        // 如果选中的是文件夹，显示文件夹信息
                        UpdateStatus($"选中文件夹: {selectedItem.Name}", true);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理项目树选择变化时发生错误");
                UpdateStatus("加载文档失败", false);
            }
        }

        private async void ProjectTreeView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            try
            {
                if (ProjectTreeView.SelectedItem is ViewModels.ProjectTreeItem selectedItem)
                {
                    _logger.LogInformation($"双击项目树项目: 名称={selectedItem.Name}, 类型={selectedItem.Type}, 路径={selectedItem.FilePath}");

                    // 如果双击的是文件夹，进入该文件夹
                    if (selectedItem.Type == ViewModels.ProjectTreeItemType.Project &&
                        !string.IsNullOrEmpty(selectedItem.FilePath) &&
                        Directory.Exists(selectedItem.FilePath))
                    {
                        _logger.LogInformation($"准备进入项目文件夹: {selectedItem.FilePath}");
                        await EnterProjectFolderAsync(selectedItem);
                    }
                    // 如果双击的是文档，确保已加载到编辑器
                    else if (selectedItem.Type == ViewModels.ProjectTreeItemType.Document &&
                             !string.IsNullOrEmpty(selectedItem.FilePath) &&
                             File.Exists(selectedItem.FilePath))
                    {
                        await DocumentEditorControl.LoadDocumentAsync(selectedItem.FilePath);
                        UpdateStatus($"已打开文档: {selectedItem.Name}", true);
                    }
                    else
                    {
                        _logger.LogWarning($"双击项目树项目不满足条件: 类型={selectedItem.Type}, 路径存在={!string.IsNullOrEmpty(selectedItem.FilePath) && Directory.Exists(selectedItem.FilePath)}");
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理项目树双击时发生错误");
                UpdateStatus("操作失败", false);
            }
        }

        private void TreeViewItem_Expanded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (sender is TreeViewItem treeViewItem && treeViewItem.DataContext is ViewModels.ProjectTreeItem item)
                {
                    _logger.LogInformation($"展开树节点: {item.Name}");

                    // 如果是文件夹类型且有路径，懒加载子项
                    if (item.Type == ViewModels.ProjectTreeItemType.Project &&
                        !string.IsNullOrEmpty(item.FilePath) &&
                        Directory.Exists(item.FilePath))
                    {
                        LoadFolderChildrenLazy(item);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理树节点展开时发生错误");
            }
        }

        private void TreeViewItem_Collapsed(object sender, RoutedEventArgs e)
        {
            try
            {
                if (sender is TreeViewItem treeViewItem && treeViewItem.DataContext is ViewModels.ProjectTreeItem item)
                {
                    _logger.LogInformation($"折叠树节点: {item.Name}");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理树节点折叠时发生错误");
            }
        }

        private void HistoryProjectListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // 当前只是选择变化，不执行任何操作
            // 实际的打开操作通过右键菜单或双击来执行
        }

        /// <summary>
        /// 历史项目列表双击事件
        /// </summary>
        private async void HistoryProjectListBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            try
            {
                if (HistoryProjectListBox.SelectedItem is ProjectHistory selectedHistory)
                {
                    // 调用打开历史项目的方法
                    await OpenHistoryProjectAsync(selectedHistory);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "双击打开历史项目失败");
                UpdateStatus("打开项目失败", false);
                MessageBox.Show($"打开失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        // 右键菜单事件处理
        private void CopyItem_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var selectedItem = ProjectTreeView.SelectedItem as ViewModels.ProjectTreeItem;
                if (selectedItem == null)
                {
                    MessageBox.Show("请先选择一个项目", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                if (!string.IsNullOrEmpty(selectedItem.FilePath) && File.Exists(selectedItem.FilePath))
                {
                    // 复制文件
                    var files = new System.Collections.Specialized.StringCollection();
                    files.Add(selectedItem.FilePath);
                    Clipboard.SetFileDropList(files);
                    UpdateStatus($"已复制文件: {selectedItem.Name}", true);
                    _logger.LogInformation($"复制文件: {selectedItem.FilePath}");
                }
                else if (selectedItem.Type == ViewModels.ProjectTreeItemType.Project)
                {
                    // 对于文件夹，复制整个文件夹路径
                    var folderPath = GetFolderPath(selectedItem);
                    if (!string.IsNullOrEmpty(folderPath) && Directory.Exists(folderPath))
                    {
                        var files = new System.Collections.Specialized.StringCollection();
                        files.Add(folderPath);
                        Clipboard.SetFileDropList(files);
                        UpdateStatus($"已复制文件夹: {selectedItem.Name}", true);
                        _logger.LogInformation($"复制文件夹: {folderPath}");
                    }
                    else
                    {
                        MessageBox.Show("无法获取文件夹路径", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
                else
                {
                    MessageBox.Show("无法复制该项目", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "复制失败");
                MessageBox.Show($"复制失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void PasteItem_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!Clipboard.ContainsFileDropList())
                {
                    MessageBox.Show("剪贴板中没有文件", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                var selectedItem = ProjectTreeView.SelectedItem as ViewModels.ProjectTreeItem;
                var targetDirectory = GetTargetPasteDirectory(selectedItem);

                if (string.IsNullOrEmpty(targetDirectory) || !Directory.Exists(targetDirectory))
                {
                    MessageBox.Show("无法确定粘贴目标目录", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                var files = Clipboard.GetFileDropList();
                if (files != null)
                {
                    foreach (string sourceFile in files)
                    {
                        if (!string.IsNullOrEmpty(sourceFile) && File.Exists(sourceFile))
                        {
                            var fileName = Path.GetFileName(sourceFile);
                            var targetFile = Path.Combine(targetDirectory, fileName);
                            File.Copy(sourceFile, targetFile, true);
                            _logger.LogInformation($"粘贴文件: {sourceFile} -> {targetFile}");
                        }
                        else if (!string.IsNullOrEmpty(sourceFile) && Directory.Exists(sourceFile))
                        {
                            var dirName = Path.GetFileName(sourceFile);
                            var targetDir = Path.Combine(targetDirectory, dirName);
                            CopyDirectory(sourceFile, targetDir);
                            _logger.LogInformation($"粘贴文件夹: {sourceFile} -> {targetDir}");
                        }
                    }

                    UpdateStatus("粘贴完成", true);
                    await RefreshProjectNavigation();
                }
                else
                {
                    MessageBox.Show("剪贴板中没有有效的文件", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "粘贴失败");
                MessageBox.Show($"粘贴失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 重命名文件或文件夹
        /// </summary>
        private async void RenameItem_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var selectedItem = ProjectTreeView.SelectedItem as ViewModels.ProjectTreeItem;
                if (selectedItem == null)
                {
                    MessageBox.Show("请先选择一个文件或文件夹", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                // 检查是否有有效的文件路径
                if (string.IsNullOrEmpty(selectedItem.FilePath) || !selectedItem.HasValidPath)
                {
                    MessageBox.Show("选中的项目没有有效的文件路径", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                // 获取当前文件/文件夹的信息
                var currentPath = selectedItem.FilePath;
                var currentName = Path.GetFileName(currentPath);
                var parentDirectory = Path.GetDirectoryName(currentPath);
                var isDirectory = Directory.Exists(currentPath);
                var isFile = File.Exists(currentPath);

                if (!isDirectory && !isFile)
                {
                    MessageBox.Show("选中的文件或文件夹不存在", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                // 显示重命名对话框
                var newName = await ShowRenameDialogAsync(currentName, isDirectory);
                if (string.IsNullOrWhiteSpace(newName) || newName == currentName)
                {
                    return; // 用户取消或没有更改
                }

                // 验证新名称
                if (!IsValidFileName(newName))
                {
                    MessageBox.Show("文件名包含无效字符，请使用有效的文件名", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                // 构建新路径
                var newPath = Path.Combine(parentDirectory!, newName);

                // 检查新路径是否已存在
                if ((isDirectory && Directory.Exists(newPath)) || (isFile && File.Exists(newPath)))
                {
                    MessageBox.Show("目标名称已存在，请选择其他名称", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                // 执行重命名
                UpdateStatus($"正在重命名 {(isDirectory ? "文件夹" : "文件")}...", true);

                if (isDirectory)
                {
                    Directory.Move(currentPath, newPath);
                }
                else
                {
                    File.Move(currentPath, newPath);
                }

                // 更新项目树项的信息
                selectedItem.Name = newName;
                selectedItem.FilePath = newPath;

                // 刷新项目导航
                await RefreshProjectNavigation();

                UpdateStatus($"{(isDirectory ? "文件夹" : "文件")}重命名成功", true);
                _logger.LogInformation($"重命名成功: {currentPath} -> {newPath}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "重命名失败");
                UpdateStatus("重命名失败", false);
                MessageBox.Show($"重命名失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 显示重命名对话框
        /// </summary>
        private async Task<string?> ShowRenameDialogAsync(string currentName, bool isDirectory)
        {
            return await Task.Run(() =>
            {
                return Dispatcher.Invoke(() =>
                {
                    var dialog = new Views.RenameDialog(currentName, isDirectory)
                    {
                        Owner = this
                    };

                    if (dialog.ShowDialog() == true)
                    {
                        return dialog.NewName;
                    }
                    return null;
                });
            });
        }

        /// <summary>
        /// 验证文件名是否有效
        /// </summary>
        private bool IsValidFileName(string fileName)
        {
            if (string.IsNullOrWhiteSpace(fileName))
                return false;

            // 检查是否包含无效字符
            var invalidChars = Path.GetInvalidFileNameChars();
            if (fileName.Any(c => invalidChars.Contains(c)))
                return false;

            // 检查是否为保留名称
            var reservedNames = new[] { "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9" };
            var nameWithoutExtension = Path.GetFileNameWithoutExtension(fileName).ToUpper();
            if (reservedNames.Contains(nameWithoutExtension))
                return false;

            // 检查长度
            if (fileName.Length > 255)
                return false;

            return true;
        }

        private void ShowPath_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var selectedItem = ProjectTreeView.SelectedItem as ViewModels.ProjectTreeItem;
                if (selectedItem == null)
                {
                    MessageBox.Show("请先选择一个项目", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                string path = string.Empty;
                if (!string.IsNullOrEmpty(selectedItem.FilePath))
                {
                    path = selectedItem.FilePath;
                }
                else
                {
                    path = GetFolderPath(selectedItem);
                }

                if (!string.IsNullOrEmpty(path))
                {
                    // 将路径复制到剪贴板
                    Clipboard.SetText(path);
                    MessageBox.Show($"路径: {path}\n\n路径已复制到剪贴板", "文件路径",
                        MessageBoxButton.OK, MessageBoxImage.Information);
                    _logger.LogInformation($"查看路径: {path}");
                }
                else
                {
                    MessageBox.Show("无法获取路径信息", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查看路径失败");
                MessageBox.Show($"查看路径失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void OpenInExplorer_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var selectedItem = ProjectTreeView.SelectedItem as ViewModels.ProjectTreeItem;
                if (selectedItem == null)
                {
                    MessageBox.Show("请先选择一个项目", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                string path = string.Empty;
                if (!string.IsNullOrEmpty(selectedItem.FilePath) && File.Exists(selectedItem.FilePath))
                {
                    // 选中文件并打开资源管理器
                    System.Diagnostics.Process.Start("explorer.exe", $"/select,\"{selectedItem.FilePath}\"");
                    _logger.LogInformation($"在资源管理器中打开文件: {selectedItem.FilePath}");
                }
                else
                {
                    path = GetFolderPath(selectedItem);
                    if (!string.IsNullOrEmpty(path) && Directory.Exists(path))
                    {
                        System.Diagnostics.Process.Start("explorer.exe", path);
                        _logger.LogInformation($"在资源管理器中打开文件夹: {path}");
                    }
                    else
                    {
                        MessageBox.Show("无法获取路径信息", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "在资源管理器中打开失败");
                MessageBox.Show($"在资源管理器中打开失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void DeleteItem_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var selectedItem = ProjectTreeView.SelectedItem as ViewModels.ProjectTreeItem;
                if (selectedItem == null)
                {
                    MessageBox.Show("请先选择一个项目", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                string itemPath = string.Empty;
                string itemType = string.Empty;

                if (!string.IsNullOrEmpty(selectedItem.FilePath) && File.Exists(selectedItem.FilePath))
                {
                    itemPath = selectedItem.FilePath;
                    itemType = "文件";
                }
                else
                {
                    itemPath = GetFolderPath(selectedItem);
                    itemType = "文件夹";
                }

                if (string.IsNullOrEmpty(itemPath))
                {
                    MessageBox.Show("无法获取路径信息", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                var result = MessageBox.Show($"确定要删除{itemType} \"{selectedItem.Name}\" 吗？\n\n路径: {itemPath}",
                    "确认删除", MessageBoxButton.YesNo, MessageBoxImage.Question);

                if (result == MessageBoxResult.Yes)
                {
                    if (itemType == "文件")
                    {
                        File.Delete(itemPath);
                    }
                    else
                    {
                        Directory.Delete(itemPath, true);
                    }

                    UpdateStatus($"已删除{itemType}: {selectedItem.Name}", true);
                    _logger.LogInformation($"删除{itemType}: {itemPath}");
                    await RefreshProjectNavigation();
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除失败");
                MessageBox.Show($"删除失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void RefreshHistory_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                UpdateStatus("正在刷新历史项目...", true);
                await LoadHistoryProjectsAsync();
                UpdateStatus("历史项目已刷新", true);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "刷新历史项目失败");
                UpdateStatus("刷新历史项目失败", false);
                MessageBox.Show($"刷新失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void CleanupInvalidHistory_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                UpdateStatus("正在检查无效的历史记录...", true);

                var invalidHistories = await _historyService.GetInvalidHistoryAsync();
                if (invalidHistories.Count == 0)
                {
                    UpdateStatus("没有发现无效的历史记录", true);
                    MessageBox.Show("没有发现无效的历史记录", "信息", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                var result = MessageBox.Show(
                    $"发现 {invalidHistories.Count} 个无效的历史记录（路径不存在），是否清理？",
                    "确认清理",
                    MessageBoxButton.YesNo,
                    MessageBoxImage.Question);

                if (result == MessageBoxResult.Yes)
                {
                    UpdateStatus("正在清理无效记录...", true);
                    var cleanedCount = await _historyService.CleanupInvalidHistoryAsync();
                    await LoadHistoryProjectsAsync();
                    UpdateStatus($"已清理 {cleanedCount} 个无效记录", true);
                    MessageBox.Show($"已清理 {cleanedCount} 个无效记录", "清理完成", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "清理无效历史记录失败");
                UpdateStatus("清理无效记录失败", false);
                MessageBox.Show($"清理失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 清理重复的历史记录
        /// </summary>
        private async void CleanupDuplicateHistory_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                UpdateStatus("正在检查重复的历史记录...", true);

                var duplicateHistories = await _historyService.GetDuplicateHistoryAsync();
                if (duplicateHistories.Count == 0)
                {
                    UpdateStatus("没有发现重复的历史记录", true);
                    MessageHelper.ShowInformation(
                        "没有发现重复的历史记录",
                        "信息",
                        "系统已检查所有历史记录，未发现重复项。您的历史记录数据是干净的。",
                        this);
                    return;
                }

                var result = MessageHelper.ShowOperationConfirmation(
                    $"清理 {duplicateHistories.Count} 个重复的历史记录（相同路径）",
                    "清理后将保留最新访问的记录，合并访问次数和收藏状态。\n重复的记录将被永久删除。",
                    "确认清理",
                    this);

                if (result == MessageBoxResult.Yes)
                {
                    UpdateStatus("正在清理重复记录...", true);
                    var cleanedCount = await _historyService.CleanupDuplicateHistoryAsync();
                    await LoadHistoryProjectsAsync();
                    UpdateStatus($"已清理 {cleanedCount} 个重复记录", true);
                    MessageBox.Show($"已清理 {cleanedCount} 个重复记录", "清理完成", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "清理重复历史记录失败");
                UpdateStatus("清理重复记录失败", false);
                MessageBox.Show($"清理失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 获取文件夹路径
        /// </summary>
        private string GetFolderPath(ViewModels.ProjectTreeItem item)
        {
            if (item == null) return string.Empty;

            // 如果是文件，返回其所在目录
            if (!string.IsNullOrEmpty(item.FilePath) && File.Exists(item.FilePath))
            {
                return Path.GetDirectoryName(item.FilePath) ?? string.Empty;
            }

            // 如果是项目文件夹，直接返回其FilePath（项目根路径）
            if (item.Type == ViewModels.ProjectTreeItemType.Project && !string.IsNullOrEmpty(item.FilePath))
            {
                return item.FilePath;
            }

            // 如果是项目根目录但FilePath为空，使用当前项目的RootPath
            if (item.Type == ViewModels.ProjectTreeItemType.Project && _currentProject != null)
            {
                return _currentProject.RootPath;
            }

            return string.Empty;
        }

        /// <summary>
        /// 获取粘贴目标目录
        /// </summary>
        private string GetTargetPasteDirectory(ViewModels.ProjectTreeItem? selectedItem)
        {
            if (selectedItem == null)
            {
                // 如果没有选中项目，使用当前项目根目录
                return _currentProject?.RootPath ?? string.Empty;
            }

            // 如果选中的是文件，使用其所在目录
            if (!string.IsNullOrEmpty(selectedItem.FilePath) && File.Exists(selectedItem.FilePath))
            {
                return Path.GetDirectoryName(selectedItem.FilePath) ?? string.Empty;
            }

            // 如果选中的是文件夹，使用该文件夹
            if (selectedItem.Type == ViewModels.ProjectTreeItemType.Project)
            {
                return GetFolderPath(selectedItem);
            }

            // 默认使用项目根目录
            return _currentProject?.RootPath ?? string.Empty;
        }

        /// <summary>
        /// 复制目录及其所有内容
        /// </summary>
        private void CopyDirectory(string sourceDir, string targetDir)
        {
            if (!Directory.Exists(sourceDir))
                return;

            if (!Directory.Exists(targetDir))
                Directory.CreateDirectory(targetDir);

            // 复制文件
            foreach (string file in Directory.GetFiles(sourceDir))
            {
                string fileName = Path.GetFileName(file);
                string targetFile = Path.Combine(targetDir, fileName);
                File.Copy(file, targetFile, true);
            }

            // 递归复制子目录
            foreach (string subDir in Directory.GetDirectories(sourceDir))
            {
                string dirName = Path.GetFileName(subDir);
                string targetSubDir = Path.Combine(targetDir, dirName);
                CopyDirectory(subDir, targetSubDir);
            }
        }

        private async void ClearHistory_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var result = MessageBox.Show(
                    "确定要清空所有历史记录吗？此操作不可撤销。",
                    "确认清空",
                    MessageBoxButton.YesNo,
                    MessageBoxImage.Question);

                if (result == MessageBoxResult.Yes)
                {
                    UpdateStatus("正在清空历史记录...", true);
                    await _historyService.ClearAllHistoryAsync();
                    await LoadHistoryProjectsAsync();
                    UpdateStatus("历史记录已清空", true);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "清空历史记录失败");
                UpdateStatus("清空历史记录失败", false);
                MessageBox.Show($"清空失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void ToggleFavorite_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (sender is Button button && button.Tag is ProjectHistory selectedHistory)
                {
                    var newFavoriteStatus = !selectedHistory.IsFavorite;
                    UpdateStatus($"正在{(newFavoriteStatus ? "添加到" : "从")}收藏{(newFavoriteStatus ? "" : "中移除")}...", true);

                    await _historyService.SetFavoriteAsync(selectedHistory.RootPath, newFavoriteStatus);
                    await LoadHistoryProjectsAsync();

                    UpdateStatus($"项目已{(newFavoriteStatus ? "添加到收藏" : "从收藏中移除")}", true);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "切换收藏状态失败");
                UpdateStatus("切换收藏状态失败", false);
                MessageBox.Show($"操作失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 退出当前项目
        /// </summary>
        private void ExitCurrentProject_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_currentProject == null)
                {
                    UpdateStatus("当前没有打开的项目", false);
                    return;
                }

                var result = MessageBox.Show(
                    $"确定要退出当前项目 '{_currentProject.Name}' 吗？",
                    "确认退出",
                    MessageBoxButton.YesNo,
                    MessageBoxImage.Question);

                if (result == MessageBoxResult.Yes)
                {
                    var projectName = _currentProject.Name;
                    _currentProject = null;

                    // 清空项目树
                    if (_viewModel != null)
                    {
                        _viewModel.ProjectItems.Clear();
                        _viewModel.CurrentProjectName = "未选择项目";
                    }

                    // 更新文档编辑器状态
                    DocumentEditorControl?.UpdateDocumentStatus("未打开项目");
                    UpdateStatus($"已退出项目: {projectName}", true);
                    _logger.LogInformation($"退出项目: {projectName}");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "退出当前项目失败");
                UpdateStatus("退出项目失败", false);
                MessageBox.Show($"退出失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 刷新当前项目
        /// </summary>
        private async void RefreshCurrentProject_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_currentProject == null)
                {
                    UpdateStatus("当前没有打开的项目", false);
                    return;
                }

                UpdateStatus("正在刷新当前项目...", true);
                await RefreshProjectNavigation();
                UpdateStatus("当前项目已刷新", true);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "刷新当前项目失败");
                UpdateStatus("刷新项目失败", false);
                MessageBox.Show($"刷新失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void OpenHistoryProject_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (HistoryProjectListBox.SelectedItem is ProjectHistory selectedHistory)
                {
                    await OpenHistoryProjectAsync(selectedHistory);
                }
                else
                {
                    MessageBox.Show("请先选择一个历史项目。", "提示",
                                  MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "打开历史项目失败");
                UpdateStatus("打开历史项目失败", false);
                MessageBox.Show($"打开项目失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 打开历史项目
        /// </summary>
        private async Task OpenHistoryProjectAsync(ProjectHistory selectedHistory)
        {
            if (!_historyService.IsProjectPathValid(selectedHistory.RootPath))
            {
                MessageBox.Show($"项目路径不存在: {selectedHistory.RootPath}", "路径错误",
                              MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            UpdateStatus($"正在打开项目: {selectedHistory.Name}", true);

            // 更新历史记录
            await _historyService.AddOrUpdateHistoryAsync(
                selectedHistory.RootPath,
                selectedHistory.Name,
                selectedHistory.Type);

            // 创建项目对象
            _currentProject = new Project
            {
                Id = 1, // 临时ID
                Name = selectedHistory.Name,
                RootPath = selectedHistory.RootPath,
                Type = selectedHistory.Type,
                CreatedAt = DateTime.Now,
                UpdatedAt = DateTime.Now
            };

            // 加载项目文件夹内容
            LoadProjectFolder(selectedHistory.RootPath);

            // 刷新历史列表
            await LoadHistoryProjectsAsync();

            // 更新项目信息显示
            UpdateProjectInfoDisplay();

            UpdateStatus($"项目已打开: {selectedHistory.Name}", true);
            _logger.LogInformation($"从历史记录打开项目: {selectedHistory.RootPath}");
        }

        /// <summary>
        /// 更新项目信息显示
        /// </summary>
        private void UpdateProjectInfoDisplay()
        {
            try
            {
                if (_currentProject != null)
                {
                    DocumentEditorControl?.UpdateDocumentStatus($"项目: {_currentProject.Name}");
                    _logger.LogDebug($"更新项目信息显示: {_currentProject.Name}");
                }
                else
                {
                    DocumentEditorControl?.UpdateDocumentStatus("未打开项目");
                }

                // 同步Agent助手的项目信息
                SyncAgentChatProject();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新项目信息显示失败");
                DocumentEditorControl?.UpdateDocumentStatus("项目信息错误");
            }
        }

        /// <summary>
        /// 同步Agent助手的项目信息
        /// </summary>
        private void SyncAgentChatProject()
        {
            try
            {
                if (_agentChatDialog != null)
                {
                    _agentChatDialog.SyncCurrentProject(_currentProject);
                    _logger.LogInformation($"已同步Agent助手项目信息: {(_currentProject?.Name ?? "无项目")}");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "同步Agent助手项目信息时发生错误");
            }
        }

        /// <summary>
        /// 系统监控数据更新事件处理
        /// </summary>
        private void SystemMonitor_DataUpdated(object? sender, SystemMonitorEventArgs e)
        {
            try
            {
                // 系统监控信息现在由DocumentEditor处理
                _logger.LogDebug($"系统监控数据已更新 - CPU: {e.ResourceInfo.Cpu.UsagePercentage:F1}%, 内存: {e.ResourceInfo.Memory.UsagePercentage:F1}%, GPU: {e.ResourceInfo.Gpu.UsagePercentage:F1}%");

                // 注释掉原来的UI更新代码，因为控件已移到DocumentEditor
                /*
                // 确保在UI线程上更新界面
                Dispatcher.Invoke(() =>
                {
                    // 更新AI模型信息
                    var displayPlatformName = GetFriendlyPlatformName(e.ModelInfo.Platform);
                    // 以下代码已注释，因为相关控件已移到DocumentEditor
                    // ModelPlatformText.Text = displayPlatformName;
                    // ModelNameText.Text = e.ModelInfo.ModelName;
                    // ... 其他UI更新代码
                });
                */
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "更新系统监控显示失败");
            }
        }



        /// <summary>
        /// 窗口关闭时清理资源
        /// </summary>
        protected override void OnClosed(EventArgs e)
        {
            try
            {
                _systemMonitorService?.StopMonitoring();
                _timer?.Stop();
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "清理资源时发生错误");
            }

            base.OnClosed(e);
        }

        private void OpenHistoryInExplorer_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (HistoryProjectListBox.SelectedItem is ProjectHistory selectedHistory)
                {
                    if (_historyService.IsProjectPathValid(selectedHistory.RootPath))
                    {
                        System.Diagnostics.Process.Start("explorer.exe", selectedHistory.RootPath);
                        UpdateStatus($"已在资源管理器中打开: {selectedHistory.Name}", true);
                    }
                    else
                    {
                        MessageBox.Show($"项目路径不存在: {selectedHistory.RootPath}", "路径错误",
                                      MessageBoxButton.OK, MessageBoxImage.Warning);
                    }
                }
                else
                {
                    MessageBox.Show("请先选择一个历史项目。", "提示",
                                  MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "在资源管理器中打开历史项目失败");
                MessageBox.Show($"打开失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void RemoveFromHistory_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (HistoryProjectListBox.SelectedItem is ProjectHistory selectedHistory)
                {
                    var result = MessageBox.Show(
                        $"确定要从历史记录中移除项目 '{selectedHistory.Name}' 吗？",
                        "确认移除",
                        MessageBoxButton.YesNo,
                        MessageBoxImage.Question);

                    if (result == MessageBoxResult.Yes)
                    {
                        UpdateStatus($"正在移除项目: {selectedHistory.Name}", true);
                        await _historyService.RemoveHistoryAsync(selectedHistory.RootPath);
                        await LoadHistoryProjectsAsync();
                        UpdateStatus("项目已从历史记录中移除", true);
                    }
                }
                else
                {
                    MessageBox.Show("请先选择要移除的项目", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "从历史记录中移除项目失败");
                UpdateStatus("移除项目失败", false);
                MessageBox.Show($"移除失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 获取用户友好的平台显示名称
        /// </summary>
        /// <param name="platformName">内部平台名称</param>
        /// <returns>用户友好的显示名称</returns>
        private string GetFriendlyPlatformName(string? platformName)
        {
            return platformName switch
            {
                "LMStudio" => "LM STUDIO",
                "ZhipuAI" => "智谱AI",
                "DeepSeek" => "DEEPSEEK",
                "Ollama" => "OLLAMA",
                _ => platformName ?? "未知平台"
            };
        }

        #region AI输出预览区域相关方法

        /// <summary>
        /// 显示预览区域
        /// </summary>
        /// <param name="content">预览内容</param>
        /// <param name="title">内容标题</param>
        private void ShowPreviewArea(string content, string title = "")
        {
            try
            {
                // 使用文档编辑器的预览功能
                DocumentEditorControl.ShowPreview(content, title);
                _logger.LogInformation($"AI输出预览已显示，内容长度: {content?.Length ?? 0}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "显示预览区域时发生错误");
                UpdateStatus("显示预览失败", false);
            }
        }

        /// <summary>
        /// 计算文本字数
        /// </summary>
        private int CountWords(string text)
        {
            if (string.IsNullOrWhiteSpace(text))
                return 0;

            // 简单的字数统计，去除空白字符
            return text.Replace(" ", "").Replace("\t", "").Replace("\n", "").Replace("\r", "").Length;
        }

        /// <summary>
        /// 保存内容为Word文档
        /// </summary>
        private void SaveContentAsDocx(string filePath, string content)
        {
            using var document = DocX.Create(filePath);
            document.InsertParagraph(content);
            document.Save();
        }

        /// <summary>
        /// 获取或创建章节重写服务
        /// </summary>
        private Services.ChapterRewriteService GetOrCreateChapterRewriteService()
        {
            // 这里应该从依赖注入容器获取，暂时直接创建
            var chapterRewriteLogger = App.ServiceProvider?.GetService<ILogger<Services.ChapterRewriteService>>();
            return new Services.ChapterRewriteService(_aiService, chapterRewriteLogger ?? _logger as ILogger<Services.ChapterRewriteService>);
        }

        #region 智能续写辅助方法

        /// <summary>
        /// 智能分析续写上下文
        /// </summary>
        private async Task<SmartContextResult> AnalyzeSmartContextForContinuationAsync(string fullText, int caretOffset)
        {
            var result = new SmartContextResult();

            if (string.IsNullOrEmpty(fullText) || caretOffset <= 0)
                return result;

            // 获取光标前的文本
            var previousText = fullText.Substring(0, Math.Min(caretOffset, fullText.Length));

            // 获取最后一段作为上下文（最多1500字符）
            var contextLength = Math.Min(1500, previousText.Length);
            result.PreviousContext = previousText.Substring(Math.Max(0, previousText.Length - contextLength));

            // 获取最后一句话
            var sentences = result.PreviousContext.Split(new char[] { '。', '！', '？', '.', '!', '?' }, StringSplitOptions.RemoveEmptyEntries);
            result.LastSentence = sentences.LastOrDefault()?.Trim() ?? "";

            // 尝试获取章节细纲
            result.ChapterOutline = await DocumentEditorControl.GetCurrentChapterOutlineAsync();

            // 分析当前位置（开头、中间、结尾）
            result.CurrentPosition = AnalyzeCurrentPosition(fullText, caretOffset);

            return result;
        }

        /// <summary>
        /// 构建智能续写提示词
        /// </summary>
        private async Task<string> BuildSmartContinuationPromptAsync(SmartContextResult context)
        {
            var prompt = new System.Text.StringBuilder();

            prompt.AppendLine("你是一位专业的小说作家，现在需要根据已有内容进行续写。");
            prompt.AppendLine();

            // 添加章节细纲信息
            if (!string.IsNullOrEmpty(context.ChapterOutline))
            {
                prompt.AppendLine("章节细纲：");
                prompt.AppendLine(context.ChapterOutline);
                prompt.AppendLine();
            }

            prompt.AppendLine("已有内容：");
            prompt.AppendLine(context.PreviousContext);
            prompt.AppendLine();

            prompt.AppendLine("续写要求：");
            prompt.AppendLine("1. 紧接着已有内容的最后一个字开始续写");
            prompt.AppendLine("2. 不要重复已有内容中的任何文字");
            prompt.AppendLine("3. 保持文风和叙述风格的一致性");
            prompt.AppendLine("4. 根据章节细纲推进剧情发展");
            prompt.AppendLine("5. 确保人物性格和行为逻辑的连贯性");
            prompt.AppendLine("6. 生成约500-800字的续写内容");

            // 根据当前位置调整续写策略
            switch (context.CurrentPosition)
            {
                case "beginning":
                    prompt.AppendLine("7. 当前处于章节开头，注重场景设定和人物介绍");
                    break;
                case "middle":
                    prompt.AppendLine("7. 当前处于章节中段，注重情节推进和冲突发展");
                    break;
                case "ending":
                    prompt.AppendLine("7. 当前处于章节末尾，注重情节收束和悬念设置");
                    break;
            }

            prompt.AppendLine();
            prompt.AppendLine("请直接开始续写，不要添加任何解释或标题：");

            return prompt.ToString();
        }

        /// <summary>
        /// 清理续写内容，避免重复
        /// </summary>
        private string CleanContinuationText(string continuationText, string lastSentence)
        {
            if (string.IsNullOrEmpty(continuationText))
                return string.Empty;

            var cleaned = continuationText.Trim();

            // 移除可能的重复内容
            if (!string.IsNullOrEmpty(lastSentence) && cleaned.StartsWith(lastSentence))
            {
                cleaned = cleaned.Substring(lastSentence.Length).TrimStart();
            }

            // 移除开头的标点符号重复
            while (cleaned.StartsWith("。") || cleaned.StartsWith("，") || cleaned.StartsWith("、"))
            {
                cleaned = cleaned.Substring(1).TrimStart();
            }

            // 确保内容以合适的方式开始
            if (!string.IsNullOrEmpty(cleaned) && !char.IsPunctuation(cleaned[0]))
            {
                // 如果不是以标点开始，可能需要添加适当的连接
                var lastChar = lastSentence.LastOrDefault();
                if (lastChar != '。' && lastChar != '！' && lastChar != '？' && lastChar != '"' && lastChar != '"')
                {
                    // 如果上一句没有结束，直接连接
                }
                else
                {
                    // 如果上一句已结束，确保新内容适当开始
                    if (!cleaned.StartsWith("　　")) // 如果不是段落开头
                    {
                        cleaned = "　　" + cleaned; // 添加段落缩进
                    }
                }
            }

            return cleaned;
        }

        /// <summary>
        /// 分析当前在文档中的位置
        /// </summary>
        private string AnalyzeCurrentPosition(string fullText, int caretOffset)
        {
            if (string.IsNullOrEmpty(fullText))
                return "beginning";

            var totalLength = fullText.Length;
            var position = (double)caretOffset / totalLength;

            if (position < 0.3)
                return "beginning";
            else if (position > 0.7)
                return "ending";
            else
                return "middle";
        }

        /// <summary>
        /// 智能续写上下文结果
        /// </summary>
        private class SmartContextResult
        {
            public string PreviousContext { get; set; } = string.Empty;
            public string LastSentence { get; set; } = string.Empty;
            public string ChapterOutline { get; set; } = string.Empty;
            public string CurrentPosition { get; set; } = "middle";
        }

        #endregion

        #region 写作设定菜单事件

        /// <summary>
        /// 提示词设定菜单点击事件
        /// </summary>
        private void PromptConfig_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                UpdateStatus("正在打开提示词设定窗口...", false);

                var promptConfigDialog = new Views.PromptConfigDialog();
                promptConfigDialog.Owner = this;
                promptConfigDialog.ShowDialog();

                UpdateStatus("提示词设定窗口已关闭", true);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "打开提示词设定窗口时发生错误");
                UpdateStatus("打开提示词设定窗口失败", false);
                MessageHelper.ShowError(
                    "打开提示词设定窗口时发生错误。",
                    ex,
                    "错误",
                    this);
            }
        }

        /// <summary>
        /// 写书流程设定菜单点击事件
        /// </summary>
        private void WritingWorkflowConfig_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                UpdateStatus("正在打开写书流程设定窗口...", false);

                var workflowConfigDialog = new Views.WritingWorkflowConfigDialog();
                workflowConfigDialog.Owner = this;
                workflowConfigDialog.ShowDialog();

                UpdateStatus("写书流程设定窗口已关闭", true);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "打开写书流程设定窗口时发生错误");
                UpdateStatus("打开写书流程设定窗口失败", false);
                MessageBox.Show($"打开写书流程设定窗口时发生错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        #endregion

        #region 智能助手功能

        /// <summary>
        /// 打开自主规划系统
        /// </summary>
        private void AutonomousPlanning_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                UpdateStatus("正在打开自主规划系统...", true);

                if (_autonomousPlanningDialog == null || !_autonomousPlanningDialog.IsLoaded)
                {
                    _autonomousPlanningDialog = new Views.AutonomousPlanningDialog(App.ServiceProvider);
                    _autonomousPlanningDialog.Owner = this;
                }

                _autonomousPlanningDialog.Show();
                _autonomousPlanningDialog.Activate();

                UpdateStatus("自主规划系统已打开", true);
                _logger.LogInformation("用户打开了自主规划系统");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "打开自主规划系统时发生错误");
                UpdateStatus("打开自主规划系统失败", false);
                MessageBox.Show($"打开自主规划系统时发生错误：{ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 打开Agent对话
        /// </summary>
        private void AgentChat_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                UpdateStatus("正在打开Agent对话...", true);

                if (_agentChatDialog == null || !_agentChatDialog.IsLoaded)
                {
                    _agentChatDialog = new Views.AgentChatDialog(App.ServiceProvider);
                    _agentChatDialog.Owner = this;
                }

                _agentChatDialog.Show();
                _agentChatDialog.Activate();

                UpdateStatus("Agent对话已打开", true);
                _logger.LogInformation("用户打开了Agent对话");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "打开Agent对话时发生错误");
                UpdateStatus("打开Agent对话失败", false);
                MessageHelper.ShowError(
                    "打开Agent对话时发生错误。",
                    ex,
                    "错误",
                    this);
            }
        }

        #endregion

        #region 增强确认弹窗测试方法

        /// <summary>
        /// 测试增强确认弹窗功能
        /// </summary>
        private void TestEnhancedMessageDialog()
        {
            try
            {
                // 测试信息对话框
                MessageHelper.ShowInformation(
                    "这是一个增强的信息对话框示例。",
                    "信息测试",
                    "详细信息：这个对话框支持自动换行、详细信息展开、自适应大小等功能。\n\n所有控件内容都能充分展示，提供更好的用户体验。",
                    this);

                // 测试确认对话框
                var result = MessageHelper.ShowOperationConfirmation(
                    "删除所有临时文件",
                    "此操作将删除系统中的所有临时文件，包括：\n- 缓存文件\n- 日志文件\n- 临时下载文件\n\n删除后可以释放磁盘空间，但某些功能可能需要重新加载数据。",
                    "确认删除",
                    this);

                if (result == MessageBoxResult.Yes)
                {
                    MessageHelper.ShowTaskCompleted(
                        "删除临时文件",
                        "成功删除了 156 个临时文件，释放了 23.5 MB 磁盘空间。\n\n系统性能可能会有所提升。",
                        "操作完成",
                        this);
                }
            }
            catch (Exception ex)
            {
                MessageHelper.ShowError(
                    "测试增强确认弹窗时发生错误。",
                    ex,
                    "测试错误",
                    this);
            }
        }

        #endregion

        #endregion
    }
}
